[GIS] Error when using gdal/ogr and python to clip a “shp” file by a “shp”

clipogrpython

I am new to the gdal/ogr library for python and I was wondering how to clip a shp file by another shp file. I think I am having trouble with the syntax. Thanks – Stefan

I keep getting a windows error message: "WindowsError: [Error 2] The system cannot find the file specified"

import subprocess

##The features used to clip the input features.**

clipping_shp = "US_States_STATE_NAME__Oregon.shp"

##The feature class to be created.**

output_shp = "output1.shp"  

##The features to be clipped.**

input_shp = "broadcast_national_ALL.shp"

##Clipping process**

subprocess.call(["ogr2ogr", "-f", "ESRI Shapefile", "-clipsrc", clipping_shp, output_shp, input_shp])

Best Answer

One possible solution is to call ogr2ogr. It is also possible to use OGR directly in Python but this is a little bit more difficult.

Here the solution if you call ogr2ogr as a subprocess:

import subprocess

# The features used to clip the input features.
clipping_shp = "US_States_STATE_NAME__Oregon.shp"
# The feature class to be created.
output_shp = "output1.shp"  
# The features to be clipped.
input_shp = "broadcast_national_ALL.shp"

# Clipping process
subprocess.call(["ogr2ogr", "-f", "ESRI Shapefile", "-clipsrc", clipping_shp, output_shp, input_shp], shell=True)