I want to select the (Sumava) from the attribute table and then make a shapefile. My problem is I don't know which function should I use to select this area.

If any one can help me?

import ogr
import os
direction_parks = 'ArcCR500_v32/ChranenaUzemi.shp'
direction_result = 'ArcCR500_v32/result.shp'

open_parks = ogr.Open(direction_parks)
layer_park = open_parks.GetLayer(0)


number_park = layer_park.GetFeatureCount()

driver = ogr.GetDriverByName("ESRI shapefile")

if os.path.exists(direction_result):

dataset = driver.CreateDataSource(direction_result)

new_layer = dataset.CreateLayer(direction_result, geom_type= ogr.wkbPolygon)

number = 0
for j in range(0, number_park):
    h = layer_park.GetNextFeature()
    h_geometry = h.GetGeometryRef()



enter image description here

layer_park.SetAttributeFilter("NAZEV_ASCI = 'Sumava'")

You can also do this with a pure SQL statement:

open_parks.ExecuteSQL("SELECT ∗ FROM layer_name WHERE NAZEV_ASCI = ’Sumava’ ")
  • thanks it works, and how can i add data from another attribute table to the new shape file attribute table – Saeed Dec 14 '15 at 18:40
  • Just copy this layer. You've already got filter on it, so: filter= driver.CreateDataSource ( " filter.shp ") and next filter_layer = filter.CopyLayer( layer_park, ’ filter’) – dmh126 Dec 14 '15 at 18:52
  • ok,but i don't have a file like filter.shp i have a .dbf file , and i want to get the data just for my selected area(Sumava) – Saeed Dec 14 '15 at 19:22
  • can i ask what do you mean by ’ filter’ what should i insert insert of that – Saeed Dec 14 '15 at 19:59

Look at the Python GDAL/OGR Cookbook:Filter by attribute

layer_parks.SetAttributeFilter("NAZEV_ASCI= 'Sumava'")

But it is easier with Fiona, another ogr Python wrapper where everything is Python dictionaries.

with fiona.open("ChranenaUzemi.shp") as input:
    with fiona.open('result.shp', 'w', 'ESRI Shapefile', input.schema.copy(), crs=input.ces as output:
         for feature in input:
            if feature['properties']['NAZEV_ASCI'] == 'Sumava':

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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