import shapefile # Create a reader instance r = shapefile.Reader("Building_Footprint") # Create a writer instance w = shapefile.Writer(shapeType=shapefile.POLYGON) # Copy the fields to the writer w.fields = list(r.fields) # Grab the geometry and records from all features # with the correct county name selection = [] for rec in enumerate(r.records()): if rec[1][1].startswith("Hancock"): selection.append(rec) # Add the geometry and records to the writer for rec in selection: w._shapes.append(r.shape(rec[0])) w.records.append(rec[1]) # Save the new shapefile w.save("HancockFootprints")
I originally used python list comprehensions for the two loops in this example. They usually run faster than "for" loops. However some basic testing showed them to be about the same speed in this case and a little harder to read. If your selection were more complex you probably want to use a for loop anyway to select by multiple attributes or other filters.
As usual the code for this example can be found on the "geospatialpython" Google Code project in the source tree. The shapefile can be found on the same site in the download section.
No comments:
Post a Comment