2

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)

layer_park.SetAttributeFilter("???????")

number_park = layer_park.GetFeatureCount()


driver = ogr.GetDriverByName("ESRI shapefile")

if os.path.exists(direction_result):
    driver.DeleteDataSource(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()

    new_layer.CreateFeature(h)

dataset.Destroy()

enter image description here

2 Answers 2

2
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’ ")
4
  • thanks it works, and how can i add data from another attribute table to the new shape file attribute table
    – Saeed
    Commented Dec 14, 2015 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
    Commented Dec 14, 2015 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
    Commented Dec 14, 2015 at 19:22
  • can i ask what do you mean by ’ filter’ what should i insert insert of that
    – Saeed
    Commented Dec 14, 2015 at 19:59
2

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':
                 output.write(feature)

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.