fiona package

Submodules

fiona.collection module

class fiona.collection.BytesCollection(bytesbuf, **kwds)

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, ignore_fields=None, ignore_geometry=False, **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.

property bounds

Returns (minx, miny, maxx, maxy).

close()

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

property closed

False if data can be accessed, otherwise True.

property crs

Returns a Proj4 string.

property crs_wkt

Returns a WKT string.

property 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.

Note: spatial filtering using mask may be inaccurate and returning all features overlapping the envelope of mask.

flush()

Flush the buffer.

get(item)
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.

Note: spatial filtering using mask may be inaccurate and returning all features overlapping the envelope of mask.

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.

Note: spatial filtering using mask may be inaccurate and returning all features overlapping the envelope of mask.

property meta

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

next()

Returns next record from iterator.

property profile

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

property 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.

Note: spatial filtering using mask may be inaccurate and returning all features overlapping the envelope of mask.

write(record)

Stages a record for writing to disk.

writerecords(records)

Stages multiple records for writing to disk.

fiona.collection.get_filetype(bytesbuf)

Detect compression type of bytesbuf.

ZIP only. TODO: add others relevant to GDAL/OGR.

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: OSError

IO errors involving driver registration or availability.

exception fiona.errors.DatasetDeleteError

Bases: OSError

Failure to delete a dataset

exception fiona.errors.DriverError

Bases: fiona.errors.FionaValueError

Encapsulates unsupported driver and driver mode errors.

exception fiona.errors.DriverIOError

Bases: OSError

A format specific driver error.

exception fiona.errors.DriverSupportError

Bases: fiona.errors.DriverIOError

Driver does not support schema

exception fiona.errors.EnvError

Bases: fiona.errors.FionaError

Environment Errors

exception fiona.errors.FeatureWarning

Bases: UserWarning

A warning about serialization of a feature

exception fiona.errors.FieldNameEncodeError

Bases: UnicodeEncodeError

Failure to encode a field name.

exception fiona.errors.FionaDeprecationWarning

Bases: UserWarning

A warning about deprecation of Fiona features

exception fiona.errors.FionaError

Bases: Exception

Base Fiona error

exception fiona.errors.FionaValueError

Bases: ValueError

Fiona-specific value errors

exception fiona.errors.GDALVersionError

Bases: fiona.errors.FionaError

Raised if the runtime version of GDAL does not meet the required version of GDAL.

exception fiona.errors.GeometryTypeValidationError

Bases: fiona.errors.FionaValueError

Tried to write a geometry type not specified in the schema

exception fiona.errors.SchemaError

Bases: fiona.errors.FionaValueError

When a schema mapping has no properties or no geometry.

exception fiona.errors.TransactionError

Bases: RuntimeError

Failure relating to GDAL transactions

exception fiona.errors.UnsupportedGeometryTypeError

Bases: 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

class fiona.ogrext.Iterator

Bases: object

Provides iterated access to feature data.

class fiona.ogrext.KeysIterator

Bases: fiona.ogrext.Iterator

class fiona.ogrext.MemoryFileBase

Bases: object

Base for a BytesIO-like class backed by an in-memory file.

close()

Close and tear down VSI file and directory.

exists()

Test if the in-memory file exists.

bool

True if the in-memory file exists.

getbuffer()

Return a view on bytes of the file, or None.

read()

Read size bytes from MemoryFile.

seek()
tell()
write()

Write data bytes to MemoryFile

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()

Provides access to feature data by FID.

Supports Collection.__contains__().

get_crs()

Get the layer’s CRS

CRS

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

Provides access to feature data by FID.

Supports Collection.__contains__().

get_fileencoding()

DEPRECATED

get_length()
get_schema()
has_feature()

Provides access to feature data by FID.

Supports Collection.__contains__().

isactive()
start()
stop()
class fiona.ogrext.TZ(minutes)

Bases: datetime.tzinfo

utcoffset(dt)

datetime -> timedelta showing offset from UTC, negative values indicating West of UTC

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.

ext is empty or begins with a period and contains at most one period.

fiona.ogrext.featureRT()
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 date, returns a datetime tuple

text: string to be parsed

(int, int , int, int, int, int, int, int):

datetime tuple: (year, month, day, hour, minute, second, microsecond, utcoffset in minutes or None)

fiona.rfc3339.parse_datetime(text)

Given a datetime, returns a datetime tuple

text: string to be parsed

(int, int , int, int, int, int, int, int):

datetime tuple: (year, month, day, hour, minute, second, microsecond, utcoffset in minutes or None)

fiona.rfc3339.parse_time(text)

Given a time, returns a datetime tuple

text: string to be parsed

(int, int , int, int, int, int, int, int):

datetime tuple: (year, month, day, hour, minute, second, microsecond, utcoffset in minutes or None)

fiona.tool module

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 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(fp, vfs=None)

List layer names in their index order

fpURI (str or pathlib.Path), or file-like object

A dataset resource identifier or file object.

vfsstr

This is a deprecated parameter. A URI scheme such as “zip://” should be used instead.

list

A list of layer name strings.

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

Open a collection for read, append, or write

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.

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’])

fpURI (str or pathlib.Path), or file-like object

A dataset resource identifier or file object.

modestr

One of ‘r’, to read (the default); ‘a’, to append; or ‘w’, to write.

driverstr

In ‘w’ mode a format driver name is required. In ‘r’ or ‘a’ mode this parameter has no effect.

schemadict

Required in ‘w’ mode, has no effect in ‘r’ or ‘a’ mode.

crsstr or dict

Required in ‘w’ mode, has no effect in ‘r’ or ‘a’ mode.

encodingstr

Name of the encoding used to encode or decode the dataset.

layerint or str

The integer index or name of a layer in a multi-layer dataset.

vfsstr

This is a deprecated parameter. A URI scheme such as “zip://” should be used instead.

enabled_driverslist

An optional list of driver names to used when opening a collection.

crs_wktstr

An optional WKT representation of a coordinate reference system.

kwargsmapping

Other driver-specific parameters that will be interpreted by the OGR library as layer creation or opening options.

Collection

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