The Fiona library provides a simple Python API around the OGR library for data access and nothing more. This approach makes it easy to use and is less verbose than OGR while using Python. Fiona outputs GeoJSON by default. You can find a wheel file for Fiona at http://www.lfd.uci.edu/~gohlke/pythonlibs/#fiona.
As an example, we'll use the GIS_CensusTract_poly.shp
file from the dbfpy
example seen earlier in this chapter.
First we'll import fiona
and Python's pprint
module to format the output. Then, we'll open the shapefile and check its driver type:
>>> import fiona >>> import pprint >>> f = fiona.open("GIS_CensusTract_poly.shp") >>> f.driver ESRI Shapefile
Next, we'll check its coordinate reference system and get the data bounding box, as shown here:
>>> f.crs {'init': 'epsg:4269'} >>> f.bounds (-89.8744162216216, 30.161122135135138, -89.1383837783784, 30.661213864864862)
Now, we'll view the data schema as geojson
and format it using the pprint
module, as you can see in the following lines of code:
>>> pprint.pprint(f.schema) {'geometry': 'Polygon', 'properties': {'GEODB_OID': 'float:11', 'OBJECTID': 'float:11', 'PERMANE0': 'str:40', 'SOURCE_1': 'str:40', 'SOURCE_2': 'str:40', 'SOURCE_3': 'str:100', 'SOURCE_4': 'str:130', 'DATA_SE5': 'str:46', 'DISTRIB6': 'str:188', 'LOADDATE': 'date', 'QUALITY': 'str:35', 'SCALE': 'str:52', 'FCODE': 'str:38', 'STCO_FI7': 'str:5', 'STATE_NAME': 'str:140', 'COUNTY_8': 'str:60', 'CENSUST9': 'str:20', 'POPULAT10': 'float:11', 'AREASQKM': 'float:31.15', 'GNIS_ID': 'str:10', 'POPULAT11': 'float:11', 'DB2GSE_12': 'float:31.15', 'DB2GSE_13': 'float:31.15'}}
Next let's get a count of the number of features:
>>> len(list(f)) 45
Finally, we'll print one of the records as formatted GeoJSON, as shown here:
pprint.pprint(f[1]) {'geometry': {'coordinates': [[[(-89.86412366375093, 30.661213864864862), (-89.86418691770497, 30.660764012731285), (-89.86443391770518, 30.659652012730202), … 'type': 'MultiPolygon'}, 'id': '1', 'properties': {'GEODB_OID': 4360.0, 'OBJECTID': 4360.0, 'PERMANE0': '9a914eef-9249-44cf-a05f-af4b48876c59', 'SOURCE_1': 'NA', 'SOURCE_2': '20006', … 'DB2GSE_12': 351242560.967882, 'DB2GSE_13': 101775.283967268}, 'type': 'Feature'}