Author: | Sean Gillies, <sean.gillies@gmail.com> |
---|---|
Revision: | 1.0 |
Date: | 10 January 2012 |
Copyright: | This work is licensed under a Creative Commons Attribution 3.0 United States License. |
Abstract: | This document explains how to use the Fiona package for reading and writing geospatial data files. |
---|
Fiona is a Python wrapper for the OGR vector data access library. A very simple wrapper for minimalists. It reads features from files as GeoJSON-like mappings and writes the same kind of mappings as features back to files. That’s it. There are no layers, no cursors, no geometric operations, no transformations between coordinate systems. Fiona doesn’t just push the complexity of OGR around, it tries to remove as much of it as possible. Simple to understand and use, with no gotchas. Vector data access for humans.
Yes. But understand that Fiona is geared to excel in a certain range of tasks and isn’t going to be optimal for others. Fiona trades memory and speed for simplicity and reliability. It copies vector data from the data source to Python objects, where OGR’s Python bindings use C pointers. The Python objects are simpler and safer to use, but more memory intensive. Fiona’s performance is relatively more slow if you only need access to a single feature property – and of course if you just want to reproject or filter data files, nothing beats the ogr2ogr program – but Fiona’s performance is much better than OGR’s Python bindings if you want all feature data (all properties and all coordinates). The copying is a constraint, yes, but it simplifies things. With Fiona, you don’t have to track references to C objects to avoid crashes, and you can work with feature data using familiar Python mapping accessors. Less worry, less time spent reading API documentation.
In what cases would you benefit from using Fiona?
In what cases would you not benefit from using Fiona?
The canonical example for Fiona is this: copying from one shapefile to another, making a trivial transformation of feature geometry.
from fiona import collection
# Open a source of features
with collection("docs/data/test_uk.shp", "r") as source:
# Define a schema for the feature sink
schema = source.schema.copy()
schema['geometry'] = 'Point'
# Open a new sink for features
with collection(
"test_write.shp", "w",
driver=source.driver,
schema=schema,
crs=source.crs
) as sink:
# Process only the features intersecting a box
for f in source.filter(bbox=(-5.0, 55.0, 0.0, 60.0)):
# Get point on the boundary of the feature
f['geometry'] = f['geometry'] = {
'type': 'Point',
'coordinates': f['geometry']['coordinates'][0][0] }
# Stage feature for writing
sink.write(f)
# The sink shapefile is written to disk when its ``with`` block ends
TODO.