5

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?

1 Answer 1

10

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
2
  • Perfect, this is what I was looking for. Thanks mate.
    – LarsVegas
    Aug 15, 2013 at 5:28
  • 1
    I've read the same article and was surprised to find the lock on the layer even after calling del layer.
    – LarsVegas
    Sep 10, 2013 at 18:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.