1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| import shapefile
# Create a reader instance for our US Roads shapefile
# Create a writer instance copying the reader's shapefile type
save = "clip"
r = shapefile.Reader("Myfile.shp")
w = shapefile.Writer(save, r.shapeType)
# Copy the database fields to the writer
w.fields = list(r.fields)
# Our selection box that contains Puerto Rico
#personal definition of coordinates (top left and bottom right coords)
xmin = -67.5
xmax = -65.0
ymin = 17.8
ymax = 18.6
# Iterate through the shapes and attributes at the same time
for road in r.iterShapeRecords():
# Shape geometry
geom = road.shape
# Database attributes
rec = road.record
# Get the bounding box of the shape (a single road)
sxmin, symin, sxmax, symax = geom.bbox
# Compare it to our Puerto Rico bounding box.
# go to the next road as soon as a coordinate is outside the box
if sxmin < xmin:
continue
elif sxmax > xmax:
continue
elif symin < ymin:
continue
elif symax > ymax:
continue
# Road is inside our selection box.
# Add it to the new shapefile
w.shape(geom)
w.record(*rec) |
Partager