fiona package

Submodules

fiona.collection module

class fiona.collection.BytesCollection(bytesbuf)

Bases: fiona.collection.Collection

BytesCollection takes a buffer of bytes and maps that to a virtual file that can then be opened by fiona.

close()

Removes the virtual file associated with the class.

class fiona.collection.Collection(path, mode='r', driver=None, schema=None, crs=None, encoding=None, layer=None, vsi=None, archive=None, enabled_drivers=None, crs_wkt=None, **kwargs)

Bases: object

A file-like interface to features of a vector dataset

Python text file objects are iterators over lines of a file. Fiona Collections are similar iterators (not lists!) over features represented as GeoJSON-like mappings.

bounds

Returns (minx, miny, maxx, maxy).

close()

In append or write mode, flushes data to disk, then ends access.

closed

False if data can be accessed, otherwise True.

crs

Returns a Proj4 string.

crs_wkt

Returns a WKT string.

driver

Returns the name of the proper OGR driver.

filter(*args, **kwds)

Returns an iterator over records, but filtered by a test for spatial intersection with the provided bbox, a (minx, miny, maxx, maxy) tuple or a geometry mask.

Positional arguments stop or start, stop[, step] allows iteration to skip over items or stop at a specific item.

flush()

Flush the buffer.

guard_driver_mode()
items(*args, **kwds)

Returns an iterator over FID, record pairs, optionally filtered by a test for spatial intersection with the provided bbox, a (minx, miny, maxx, maxy) tuple or a geometry mask.

Positional arguments stop or start, stop[, step] allows iteration to skip over items or stop at a specific item.

keys(*args, **kwds)

Returns an iterator over FIDs, optionally filtered by a test for spatial intersection with the provided bbox, a (minx, miny, maxx, maxy) tuple or a geometry mask.

Positional arguments stop or start, stop[, step] allows iteration to skip over items or stop at a specific item.

meta

Returns a mapping with the driver, schema, crs, and additional properties.

next()

Returns next record from iterator.

profile

Returns a mapping with the driver, schema, crs, and additional properties.

schema

Returns a mapping describing the data schema.

The mapping has ‘geometry’ and ‘properties’ items. The former is a string such as ‘Point’ and the latter is an ordered mapping that follows the order of fields in the data file.

validate_record(record)

Compares the record to the collection’s schema.

Returns True if the record matches, else False.

validate_record_geometry(record)

Compares the record’s geometry to the collection’s schema.

Returns True if the record matches, else False.

values(*args, **kwds)

Returns an iterator over records, but filtered by a test for spatial intersection with the provided bbox, a (minx, miny, maxx, maxy) tuple or a geometry mask.

Positional arguments stop or start, stop[, step] allows iteration to skip over items or stop at a specific item.

write(record)

Stages a record for writing to disk.

writerecords(records)

Stages multiple records for writing to disk.

fiona.collection.vsi_path(path, vsi=None, archive=None)

fiona.compat module

fiona.crs module

Coordinate reference systems and functions

PROJ.4 is the law of this land: http://proj.osgeo.org/. But whereas PROJ.4 coordinate reference systems are described by strings of parameters such as

+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs

here we use mappings:

{‘proj’: ‘longlat’, ‘ellps’: ‘WGS84’, ‘datum’: ‘WGS84’, ‘no_defs’: True}
fiona.crs.from_epsg(code)

Given an integer code, returns an EPSG-like mapping.

Note: the input code is not validated against an EPSG database.

fiona.crs.from_string(prjs)

Turn a PROJ.4 string into a mapping of parameters.

Bare parameters like “+no_defs” are given a value of True. All keys are checked against the all_proj_keys list.

fiona.crs.to_string(crs)

Turn a parameter mapping into a more conventional PROJ.4 string.

Mapping keys are tested against the all_proj_keys list. Values of True are omitted, leaving the key bare: {‘no_defs’: True} -> “+no_defs” and items where the value is otherwise not a str, int, or float are omitted.

fiona.drvsupport module

fiona.errors module

exception fiona.errors.CRSError

Bases: fiona.errors.FionaValueError

When a crs mapping has neither init or proj items.

exception fiona.errors.DataIOError

Bases: exceptions.IOError

IO errors involving driver registration or availability.

exception fiona.errors.DriverError

Bases: fiona.errors.FionaValueError

Encapsulates unsupported driver and driver mode errors.

exception fiona.errors.FieldNameEncodeError

Bases: exceptions.UnicodeEncodeError

Failure to encode a field name.

exception fiona.errors.FionaValueError

Bases: exceptions.ValueError

Fiona-specific value errors

exception fiona.errors.SchemaError

Bases: fiona.errors.FionaValueError

When a schema mapping has no properties or no geometry.

exception fiona.errors.UnsupportedGeometryTypeError

Bases: exceptions.KeyError

When a OGR geometry type isn’t supported by Fiona.

fiona.inspector module

fiona.inspector.main(srcfile)

fiona.ogrext module

class fiona.ogrext.FeatureBuilder

Bases: object

Build Fiona features from OGR feature pointers.

No OGR objects are allocated by this function and the feature argument is not destroyed.

class fiona.ogrext.ItemsIterator

Bases: fiona.ogrext.Iterator

next
class fiona.ogrext.Iterator

Bases: object

Provides iterated access to feature data.

next
class fiona.ogrext.KeysIterator

Bases: fiona.ogrext.Iterator

next
class fiona.ogrext.NullHandler(level=0)

Bases: logging.Handler

emit()
class fiona.ogrext.OGRFeatureBuilder

Bases: object

Builds an OGR Feature from a Fiona feature mapping.

Allocates one OGR Feature which should be destroyed by the caller. Borrows a layer definition from the collection.

class fiona.ogrext.Session

Bases: object

get_crs()
get_crs_wkt()
get_driver()
get_extent()
get_feature()

Provides access to feature data by FID.

Supports Collection.__contains__().

get_fileencoding()
get_internalencoding()
get_length()
get_schema()
has_feature()

Provides access to feature data by FID.

Supports Collection.__contains__().

isactive()
start()
stop()
class fiona.ogrext.WritingSession

Bases: fiona.ogrext.Session

start()
sync()

Syncs OGR to disk.

writerecs()

Writes buffered records to OGR.

fiona.ogrext.buffer_to_virtual_file()

Maps a bytes buffer to a virtual file.

fiona.ogrext.calc_gdal_version_num()

Calculates the internal gdal version number based on major, minor and revision

fiona.ogrext.featureRT()
fiona.ogrext.get_gdal_release_name()

Return release name of gdal

fiona.ogrext.get_gdal_version_num()

Return current internal version number of gdal

fiona.ogrext.remove_virtual_file()

fiona.ogrext1 module

fiona.ogrext2 module

fiona.rfc3339 module

class fiona.rfc3339.FionaDateTimeType

Bases: str

Dates and times.

class fiona.rfc3339.FionaDateType

Bases: str

Dates without time.

class fiona.rfc3339.FionaTimeType

Bases: str

Times without dates.

class fiona.rfc3339.group_accessor(m)

Bases: object

group(i)
fiona.rfc3339.parse_date(text)

Given a RFC 3339 date, returns a tz-naive datetime tuple

fiona.rfc3339.parse_datetime(text)

Given a RFC 3339 datetime, returns a tz-naive datetime tuple

fiona.rfc3339.parse_time(text)

Given a RFC 3339 time, returns a tz-naive datetime tuple

fiona.tool module

fiona.tool

Converts Shapefiles (etc) to GeoJSON.

fiona.tool.crs_uri(crs)

Returns a CRS URN computed from a crs dict.

fiona.tool.id_record(rec)

Converts a record’s id to a blank node id and returns the record.

fiona.tool.main(args, dump_kw, item_sep, ignore_errors)

Returns 0 on success, 1 on error, for sys.exit.

fiona.tool.make_ld_context(context_items)

Returns a JSON-LD Context object.

See http://json-ld.org/spec/latest/json-ld.

fiona.tool.open_output(arg)

Returns an opened output stream.

fiona.transform module

Coordinate and geometry warping and reprojection

fiona.transform.transform(src_crs, dst_crs, xs, ys)

Transform coordinates from one reference system to another.

src_crs: str or dict
A string like ‘EPSG:4326’ or a dict of proj4 parameters like {‘proj’: ‘lcc’, ‘lat_0’: 18.0, ‘lat_1’: 18.0, ‘lon_0’: -77.0} representing the coordinate reference system on the “source” or “from” side of the transformation.
dst_crs: str or dict
A string or dict representing the coordinate reference system on the “destination” or “to” side of the transformation.
xs: sequence of float
A list or tuple of x coordinate values. Must have the same length as the ys parameter.
ys: sequence of float
A list or tuple of y coordinate values. Must have the same length as the xs parameter.
xp, yp: list of float
A pair of transformed coordinate sequences. The elements of xp and yp correspond exactly to the elements of the xs and ys input parameters.
>>> transform('EPSG:4326', 'EPSG:26953', [-105.0], [40.0])
([957097.0952383667], [378940.8419189212])
fiona.transform.transform_geom(src_crs, dst_crs, geom, antimeridian_cutting=False, antimeridian_offset=10.0, precision=-1)

Transform a geometry obj from one reference system to another.

src_crs: str or dict
A string like ‘EPSG:4326’ or a dict of proj4 parameters like {‘proj’: ‘lcc’, ‘lat_0’: 18.0, ‘lat_1’: 18.0, ‘lon_0’: -77.0} representing the coordinate reference system on the “source” or “from” side of the transformation.
dst_crs: str or dict
A string or dict representing the coordinate reference system on the “destination” or “to” side of the transformation.
geom: obj
A GeoJSON-like geometry object with ‘type’ and ‘coordinates’ members.
antimeridian_cutting: bool, optional
True to cut output geometries in two at the antimeridian, the default is ``False`.
antimeridian_offset: float, optional
A distance in decimal degrees from the antimeridian, outside of which geometries will not be cut.
precision: int, optional
Optional rounding precision of output coordinates, in number of decimal places.
obj
A new GeoJSON-like geometry with transformed coordinates. Note that if the output is at the antimeridian, it may be cut and of a different geometry type than the input, e.g., a polygon input may result in multi-polygon output.
>>> transform_geom(
...     'EPSG:4326', 'EPSG:26953',
...     {'type': 'Point', 'coordinates': [-105.0, 40.0]})
{'type': 'Point', 'coordinates': (957097.0952383667, 378940.8419189212)}

Module contents

Fiona is OGR’s neat, nimble, no-nonsense API.

Fiona provides a minimal, uncomplicated Python interface to the open source GIS community’s most trusted geodata access library and integrates readily with other Python GIS packages such as pyproj, Rtree and Shapely.

How minimal? Fiona can read features as mappings from shapefiles or other GIS vector formats and write mappings as features to files using the same formats. That’s all. There aren’t any feature or geometry classes. Features and their geometries are just data.

A Fiona feature is a Python mapping inspired by the GeoJSON format. It has id, ‘geometry`, and properties keys. The value of id is a string identifier unique within the feature’s parent collection. The geometry is another mapping with type and coordinates keys. The properties of a feature is another mapping corresponding to its attribute table. For example:

{‘id’: ‘1’,
‘geometry’: {‘type’: ‘Point’, ‘coordinates’: (0.0, 0.0)}, ‘properties’: {‘label’: u’Null Island’} }

is a Fiona feature with a point geometry and one property.

Features are read and written using objects returned by the collection function. These Collection objects are a lot like Python file objects. A Collection opened in reading mode serves as an iterator over features. One opened in a writing mode provides a write method.

Usage

Here’s an example of reading a select few polygon features from a shapefile and for each, picking off the first vertex of the exterior ring of the polygon and using that as the point geometry for a new feature writing to a “points.shp” file.

>>> import fiona
>>> with fiona.open('docs/data/test_uk.shp', 'r') as inp:
...     output_schema = inp.schema.copy()
...     output_schema['geometry'] = 'Point'
...     with collection(
...             "points.shp", "w",
...             crs=inp.crs,
...             driver="ESRI Shapefile",
...             schema=output_schema
...             ) as out:
...         for f in inp.filter(
...                 bbox=(-5.0, 55.0, 0.0, 60.0)
...                 ):
...             value = f['geometry']['coordinates'][0][0]
...             f['geometry'] = {
...                 'type': 'Point', 'coordinates': value}
...             out.write(f)

Because Fiona collections are context managers, they are closed and (in writing modes) flush contents to disk when their with blocks end.

fiona.bounds(ob)

Returns a (minx, miny, maxx, maxy) bounding box.

The ob may be a feature record or geometry.

fiona.listlayers(path, vfs=None)

Returns a list of layer names in their index order.

The required path argument may be an absolute or relative file or directory path.

A virtual filesystem can be specified. The vfs parameter may be an Apache Commons VFS style string beginning with “zip://” or “tar://””. In this case, the path must be an absolute path within that container.

fiona.open(path, mode='r', driver=None, schema=None, crs=None, encoding=None, layer=None, vfs=None, enabled_drivers=None, crs_wkt=None)

Open file at path in mode “r” (read), “a” (append), or “w” (write) and return a Collection object.

In write mode, a driver name such as “ESRI Shapefile” or “GPX” (see OGR docs or ogr2ogr --help on the command line) and a schema mapping such as:

{‘geometry’: ‘Point’,
‘properties’: [(‘class’, ‘int’), (‘label’, ‘str’),
(‘value’, ‘float’)]}

must be provided. If a particular ordering of properties (“fields” in GIS parlance) in the written file is desired, a list of (key, value) pairs as above or an ordered dict is required. If no ordering is needed, a standard dict will suffice.

A coordinate reference system for collections in write mode can be defined by the crs parameter. It takes Proj4 style mappings like

{‘proj’: ‘longlat’, ‘ellps’: ‘WGS84’, ‘datum’: ‘WGS84’,
‘no_defs’: True}

short hand strings like

EPSG:4326

or WKT representations of coordinate reference systems.

The drivers used by Fiona will try to detect the encoding of data files. If they fail, you may provide the proper encoding, such as ‘Windows-1252’ for the Natural Earth datasets.

When the provided path is to a file containing multiple named layers of data, a layer can be singled out by layer.

A virtual filesystem can be specified. The vfs parameter may be an Apache Commons VFS style string beginning with “zip://” or “tar://””. In this case, the path must be an absolute path within that container.

The drivers enabled for opening datasets may be restricted to those listed in the enabled_drivers parameter. This and the driver parameter afford much control over opening of files.

# Trying only the GeoJSON driver when opening to read, the # following raises DataIOError: fiona.open(‘example.shp’, driver=’GeoJSON’)

# Trying first the GeoJSON driver, then the Shapefile driver, # the following succeeds: fiona.open(

‘example.shp’, enabled_drivers=[‘GeoJSON’, ‘ESRI Shapefile’])
fiona.prop_type(text)

Returns a schema property’s proper Python type.

Example:

>>> prop_type('int')
<class 'int'>
>>> prop_type('str:25')
<class 'str'>
fiona.prop_width(val)

Returns the width of a str type property.

Undefined for non-str properties. Example:

>>> prop_width('str:25')
25
>>> prop_width('str')
80