[GIS] Cropping a Shapefile into a Rectangular Box with Python pyshp

extentspyshppythonshapefile

Using 'pyshp' I am hoping to reduce the set of US highway shapefiles to only those in Puerto Rico. The idea is very easy since I only need those pieces which fit into the window.

>> import shapefile
>> sf = shapefile.Reader("roadl_usa") 
>> len(sf.records())

193504

Not familiar with the writing object but hoping it's easy since I am not building from scratch. How do I select only those records in the bounding box [-67.5, -65.0] and [17.8, 18.6] and write a new shapefile?

What is the output like? I am wondering if .shx, .txt, .dbs also get exported and what they mean.


This script almost works except it leads to IndexError: list index out of range – maybe this is because I am deleting things in the process of iterating?

import shapefile
e = shapefile.Editor("roadl_usa")

prbbox = [-67.5, 17.8,-65.0, 18.6]

L = len(e.shapes())    
for t in range(L):
    if f( e.shape(t).bbox, prbbox) > 0:
        e.delete(t)

e.save('pr-roads')

Best Answer

Non-Python solution

ogr2ogr -f "ESRI Shapefile" pr-roads.shp roadl_usa.shp -clipsrc -67.5  17.8 -65.1  18.6