import shapefile
# read the shapefile
reader = shapefile.Reader("my.shp")
fields = reader.fields[1:]
field_names = [field[0] for field in fields]
buffer = []
for sr in reader.shapeRecords():
atr = dict(zip(field_names, sr.record))
geom = sr.shape.__geo_interface__
buffer.append(dict(type="Feature", \
geometry=geom, properties=atr))
# write the GeoJSON file
from json import dumps
geojson = open("pyshp-demo.json", "w")
geojson.write(dumps({"type": "FeatureCollection",\
"features": buffer}, indent=2) + "\n")
geojson.close()
Tuesday, July 23, 2013
Shapefile to GeoJSON
Here's a quick example by Martin Laloux using the new PyShp geo-interface and the built-in json module to convert a shapefile to geojson in pure Python:
Wednesday, June 26, 2013
Dots in Shapefile Names
I came across a post from another blogger recently which highlighted an issue I hadn't considered before. Most operating systems allow for an arbitrary number of periods "." in a file name. For example your shp file in a shapefile set might be named "cities.2013.v.1.2.shp". While I'm aware of that fact I did not really take it into consideration when designing PyShp. Here are some factors I did consider:
1. There are at least 3 and up to 9 file types in a single shapefile data set.
2. Dbf files are a fairly common data format for file-based databases.
3. The shx file is just an index and does not contain critical data.
Given these considerations I made it possible to just specify the the base name of a shapefile when reading or writing or you can add an extension IF you want. Pyshp doesn't rely on the extension. So in the above example I could just use "cities.2013.v.1.2" in theory.
That way if one of the files was missing or for some reason you had no control over how the file name was passed to your program the software would just work. I figured this approach would be the most robust and intuitive, user-friendly method. In fact if you DO specify a file extension PyShp just chops is off to get the base name using Python's os.path.splitext() module method and then rebuilds the requisite file names before checking to see if they even exist.
There's only one problem. If you use the base file name AND you have extra dots in your file name as in the example, Python still chops off everything after the last dot assuming it is the file extension. This functionality is fair since there's no way programatically to be sure what is an extension and what is not. You could use a look-up table in this context but that can lead to other problems. So in the above example if you pass the base file name to the PyShp Reader object the base name would be shortened to "cities.2013.v.1" which would result in IO exceptions.
The safe workaround is to just always include a three-letter extension in the file name if you might have dots. I may eventually try to program around this but it's kind of a corner case with a reasonable workaround.
Sunday, June 23, 2013
PyShp Version 1.1.7 Release
PyShp 1.1.7 is out after several months of virtually no updates. This release fixes a bunch of minor issues
plus a couple of important features. You can get it through setuptools or source from the CheeseShop: https://pypi.python.org/pypi/pyshp/1.1.7. The Google Code page is here:https://code.google.com/p/pyshp/
- Added Python geo_interface convention to export shapefiles as GeoJSON.
- Used is_string() method to detect file names passed as unicode strings (failed on unicode strings before).
- Added Reader.iterShapes() method to iterate through geometry records for parsing large files efficiently.
- Added Reader.iterRecords() method to iterate through dbf records efficiently in large files.
- Modified shape() method to use iterShapes() if shx file is not available as well as record() method.
- Fixed bug which prevents writing the number 0 to dbf fields.
- Updated shape() method to calculate and seek the start of the next record. The shapefile spec does not require the content of a geometry record to be as long as the content length defined in the header. The result is you can delete features without modifying the record header allowing for empty space in records.
- Added enforcement of closed polygons in the Writer.poly() method.
- Added unique file name generator to use if no file names are passed to a writer instance when saving (ex. w.save()). The unique file name is returned as a string.
- Updated "bbox" property documentation to match Esri specification.
The __geo_interface__ update required a polygon area calculator. This method is undocumented but you can feed a list of points representing a polygon to shapefile.signed_area(coords) and get an area calculation back. If the area is a positive number the points are clockwise (outer ring). If the area is negative then the points are in counter-clockwise order (i.e. an inner polygon ring).
Labels:
__geo_interface__,
geospatial,
gis,
pypi,
pyshp,
python,
python3,
shapefile
Monday, May 20, 2013
New __geo_interface__ for PyShp
Christian Ledermann took the initiative to fork pyshp and add the __geo_interface__ convention.
| http://twitter.com/GeoJSON |
The __geo_interface__ is a community standard riding the current "less is more" entropy wave to get away from heavy data exchange standards, make software compatible, and get some work done.
This standard is very pythonic and well thought out which is no surprise because Sean Gillies and Howard Butler are a driving forces behind it. The goal is to make moving data around among libraries with different specialties, like Shapely and PySAL, easier. It is closely tied to GeoJSON which is getting a lot of traction and shaking up the industry and community.
Christian's __geo_interface__ implementation for PyShp is here:
https://github.com/cleder/pyshp
He also wrote some ogr2ogr-style conversion samples to show you how to use it here:
https://github.com/cleder/geo_file_conv
I'm 100% behind these ideas and will roll this interface into the main trunk. But there's nothing stopping you from using Christian's fork today.
Enjoy!
Labels:
__geo_interface__,
conversion,
convert,
geojson,
geometry,
geospatial,
gis,
mapping,
point,
polygon,
pyshp,
python,
shapefile,
web
Tuesday, April 9, 2013
Add a Field to an Existing Shapefile
The dbf file of a shapefile is a simple file-based database with rows and columns. The rows are
"records" and the columns are "fields". Sometimes you want to add an additional field to the dbf file to capture some new type of information not originally included.
Today's example shows you how to use pyshp to add a new field to an existing shapefile. This operation is a two-step process. You must first update the dbf header to define the new field. Then you must update each record to account for a new column in the database so everything is balanced.
In the past, I've demonstrated modifying existing shapefiles for other reasons including merging shapefiles and deleting features in shapefiles. In every case you are actually reading in the existing shapefile, creating a new shapefile in memory and then writing out the new file either separately or on top of the old one. Even in really high-end GIS packages that's basically all you're doing. Some packages will use a temporary file in between.
Here's the example. We'll create a counter that gives us unique sample data to append to each record just so we can see the changes clearly. In the real world, you'd probably just insert a blank palce holder.
So there you have it. Overall it's a pretty simple process that can be extended to do some sophisticated operations. The sample Mississippi shapefile can be found here. But this shapefile only has one record so it's not that interesting. But it's lightweight and easy to examine the dbf file in your favorite spreadsheet program.
![]() |
Adding a field where there wasn't one before has
limitless possibilities. |
Today's example shows you how to use pyshp to add a new field to an existing shapefile. This operation is a two-step process. You must first update the dbf header to define the new field. Then you must update each record to account for a new column in the database so everything is balanced.
In the past, I've demonstrated modifying existing shapefiles for other reasons including merging shapefiles and deleting features in shapefiles. In every case you are actually reading in the existing shapefile, creating a new shapefile in memory and then writing out the new file either separately or on top of the old one. Even in really high-end GIS packages that's basically all you're doing. Some packages will use a temporary file in between.
Here's the example. We'll create a counter that gives us unique sample data to append to each record just so we can see the changes clearly. In the real world, you'd probably just insert a blank palce holder.
import shapefile
# Read in our existing shapefile
r = shapefile.Reader("Mississippi")
# Create a new shapefile in memory
w = shapefile.Writer()
# Copy over the existing fields
w.fields = list(r.fields)
# Add our new field using the pyshp API
w.field("KINSELLA", "C", "40")
# We'll create a counter in this example
# to give us sample data to add to the records
# so we know the field is working correctly.
i=1
# Loop through each record, add a column. We'll
# insert our sample data but you could also just
# insert a blank string or NULL DATA number
# as a place holder
for rec in r.records():
rec.append(i)
i+=1
# Add the modified record to the new shapefile
w.records.append(rec)
# Copy over the geometry without any changes
w._shapes.extend(r.shapes())
# Save as a new shapefile (or write over the old one)
w.save("Miss")
So there you have it. Overall it's a pretty simple process that can be extended to do some sophisticated operations. The sample Mississippi shapefile can be found here. But this shapefile only has one record so it's not that interesting. But it's lightweight and easy to examine the dbf file in your favorite spreadsheet program.
Subscribe to:
Posts (Atom)

