0

I've downloaded an openstreetmap shapefile and want to extract certain features (to make the file less heavy and have only the ones I'm interested in, for example bicycle paths from the roads). How would I do this, I can currently open the file and look at the features with this code:

from osgeo import ogr

file = ogr.Open('gis.osm_roads_free_1.shp')
shape = file.GetLayer(0)

# here I want to filter on an "fclass" value

Any suggestions on how to do this?

Yorian
  • 2,002
  • 5
  • 34
  • 60
  • what's fclass? An attribute? – Jarek.D Apr 06 '18 at 10:36
  • any how the shapefile is laid out? is it one feature per layer and you want to iterate over layers or you want to iterate over the features in layer 0? – Jarek.D Apr 06 '18 at 10:38
  • fclass is indeed an attribute, it contains the type of road (for example: highway, primary road, bycicle path, etc.). The shapefile has only one layer, in that layer it has the features (the lines of the roads). – Yorian Apr 06 '18 at 10:42

1 Answers1

0

Try this.

from osgeo import ogr

def create_filtered_shapefile(value, filter_field, in_shapefile, out_shapefile):
    input_layer = ogr.Open(in_shapefile).GetLayer()

    # Filter by our query
    query_str = '"{}" = "{}"'.format(filter_field, value)
    input_layer.SetAttributeFilter(query_str)

    # Copy Filtered Layer and Output File
    driver = ogr.GetDriverByName('ESRI Shapefile')
    out_ds = driver.CreateDataSource(out_shapefile)
    out_layer = out_ds.CopyLayer(input_layer, str(value))
    del input_layer, out_layer, out_ds
    return out_shapefile

# for example
create_filtered_shapefile('highways', 'fclass', 'gis.osm_roads_free_1.shp')
Jarek.D
  • 1,274
  • 1
  • 8
  • 18