Friday, 11 August 2017

python - OGR: How to save layer from AttributeFilter to a shapefile?


I select a subset of features from my shapefile like so:


node_lyr = nodes.GetLayer()
q_str = "%s = %i" % (field, value)
node_lyr.SetAttributeFilter(q_str)

What is the best way to make a shapefile from this subset?




Answer



You can use the ogr.DataSource.CopyLayer method.


For example:


from osgeo import ogr
inds = ogr.Open('test1.shp')
inlyr=inds.GetLayer()
inlyr.SetAttributeFilter('NAME = "a"')
drv = ogr.GetDriverByName( 'ESRI Shapefile' )
outds = drv.CreateDataSource( "test2.shp" )
outlyr = outds.CopyLayer(inlyr,'test2')

del inlyr,inds,outlyr,outds

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...