fiona package

Subpackages

Submodules

fiona.collection module

Collections provide file-like access to feature data.

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

Bases: 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, include_fields=None, wkt_version=None, allow_unsupported_drivers=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

The coordinate reference system (CRS) of the Collection.

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. An attribute filter can be set using an SQL where clause, which uses the OGR SQL dialect.

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)
get_tag_item(key, ns=None)

Returns tag item value

Parameters

key: str

The key for the metadata item to fetch.

ns: str, optional

Used to select a namespace other than the default.

Returns

str

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. An attribute filter can be set using an SQL where clause, which uses the OGR SQL dialect.

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. An attribute filter can be set using an SQL where clause, which uses the OGR SQL dialect.

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.

tags(ns=None)

Returns a dict containing copies of the dataset or layers’s tags. Tags are pairs of key and value strings. Tags belong to namespaces. The standard namespaces are: default (None) and ‘IMAGE_STRUCTURE’. Applications can create their own additional namespaces.

Parameters

ns: str, optional

Can be used to select a namespace other than the default.

Returns

dict

update_tag_item(key, tag, ns=None)

Updates the tag item value

Parameters

key: str

The key for the metadata item to set.

tag: str

The value of the metadata item to set.

ns: str, optional

Used to select a namespace other than the default.

Returns

int

update_tags(tags, ns=None)

Writes a dict containing the dataset or layers’s tags. Tags are pairs of key and value strings. Tags belong to namespaces. The standard namespaces are: default (None) and ‘IMAGE_STRUCTURE’. Applications can create their own additional namespaces.

Parameters

tags: dict

The dict of metadata items to set.

ns: str, optional

Used to select a namespace other than the default.

Returns

int

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. An attribute filter can be set using an SQL where clause, which uses the OGR SQL dialect.

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.

Note: Each call of this method will start and commit a unique transaction with the data source.

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.compat.strencode(instr, encoding='utf-8')

fiona.crs module

Coordinate reference systems, the CRS class and supporting functions.

A coordinate reference system (CRS) defines how a dataset’s pixels map to locations on, for example, a globe or the Earth. A CRS may be local or global. The GIS field shares a number of authority files that define CRS. “EPSG:32618” is the name of a regional CRS from the European Petroleum Survey Group authority file. “OGC:CRS84” is the name of a global CRS from the Open Geospatial Consortium authority. Custom CRS can be described in text using several formats. Rasterio’s CRS class is our abstraction for coordinate reference systems.

A fiona.Collection’s crs property is an instance of CRS. CRS are also used to define transformations between coordinate reference systems. These transformations are performed by the PROJ library. Rasterio does not call PROJ functions directly, but invokes them via calls to GDAL’s “OSR*” functions.

class fiona.crs.CRS(initialdata=None, **kwargs)

Bases: object

A geographic or projected coordinate reference system.

New in version 1.9.0.

CRS objects may be created by passing PROJ parameters as keyword arguments to the standard constructor or by passing EPSG codes, PROJ mappings, PROJ strings, or WKT strings to the from_epsg, from_dict, from_string, or from_wkt static methods.

Examples

The from_dict method takes PROJ parameters as keyword arguments.

>>> crs = CRS.from_dict(proj="aea")

EPSG codes may be used with the from_epsg method.

>>> crs = CRS.from_epsg(3005)

The from_string method takes a variety of input.

>>> crs = CRS.from_string("EPSG:3005")
data

A PROJ4 dict representation of the CRS.

static from_authority(auth_name, code)

Make a CRS from an authority name and code.

New in version 1.9.0.

Parameters

auth_name: str

The name of the authority.

codeint or str

The code used by the authority.

Returns

CRS

Raises

CRSError

static from_dict(initialdata=None, **kwargs)

Make a CRS from a dict of PROJ parameters or PROJ JSON.

Parameters

initialdatamapping, optional

A dictionary or other mapping

kwargsmapping, optional

Another mapping. Will be overlaid on the initialdata.

Returns

CRS

Raises

CRSError

static from_epsg(code)

Make a CRS from an EPSG code.

Parameters

codeint or str

An EPSG code. Strings will be converted to integers.

Notes

The input code is not validated against an EPSG database.

Returns

CRS

Raises

CRSError

static from_proj4(proj)

Make a CRS from a PROJ4 string.

Parameters

projstr

A PROJ4 string like “+proj=longlat …”

Returns

CRS

Raises

CRSError

static from_string(value, morph_from_esri_dialect=False)

Make a CRS from an EPSG, PROJ, or WKT string

Parameters

valuestr

An EPSG, PROJ, or WKT string.

morph_from_esri_dialectbool, optional

If True, items in the input using Esri’s dialect of WKT will be replaced by OGC standard equivalents.

Returns

CRS

Raises

CRSError

static from_user_input(value, morph_from_esri_dialect=False)

Make a CRS from a variety of inputs.

Parameters

valueobject

User input of many different kinds.

morph_from_esri_dialectbool, optional

If True, items in the input using Esri’s dialect of WKT will be replaced by OGC standard equivalents.

Returns

CRS

Raises

CRSError

static from_wkt(wkt, morph_from_esri_dialect=False)

Make a CRS from a WKT string.

Parameters

wktstr

A WKT string.

morph_from_esri_dialectbool, optional

If True, items in the input using Esri’s dialect of WKT will be replaced by OGC standard equivalents.

Returns

CRS

Raises

CRSError

get(self, item)
is_epsg_code

Test if the CRS is defined by an EPSG code.

Returns

bool

is_geographic

Test if the CRS is a geographic coordinate reference system.

Returns

bool

Raises

CRSError

is_projected

Test if the CRS is a projected coordinate reference system.

Returns

bool

Raises

CRSError

is_valid

Test that the CRS is a geographic or projected CRS.

Returns

bool

items(self)
keys(self)
linear_units

Get a short name for the linear units of the CRS.

Returns

unitsstr

“m”, “ft”, etc.

Raises

CRSError

linear_units_factor

Get linear units and the conversion factor to meters of the CRS.

Returns

unitsstr

“m”, “ft”, etc.

factorfloat

Ratio of one unit to one meter.

Raises

CRSError

to_authority(self, confidence_threshold=70)

Convert to the best match authority name and code.

For a CRS created using an EPSG code, that same value is returned. For other CRS, including custom CRS, an attempt is made to match it to definitions in authority files. Matches with a confidence below the threshold are discarded.

Parameters

confidence_thresholdint

Percent match confidence threshold (0-100).

Returns

namestr

Authority name.

codestr

Code from the authority file.

or None

to_dict(self, projjson=False)

Convert CRS to a PROJ dict.

Note

If there is a corresponding EPSG code, it will be used when returning PROJ parameter dict.

New in version 1.9.0.

Parameters

projjson: bool, default=False

If True, will convert to PROJ JSON dict (Requites GDAL 3.1+ and PROJ 6.2+). If False, will convert to PROJ parameter dict.

Returns

dict

to_epsg(self, confidence_threshold=70)

Convert to the best match EPSG code.

For a CRS created using an EPSG code, that same value is returned. For other CRS, including custom CRS, an attempt is made to match it to definitions in the EPSG authority file. Matches with a confidence below the threshold are discarded.

Parameters

confidence_thresholdint

Percent match confidence threshold (0-100).

Returns

int or None

Raises

CRSError

to_proj4(self)

Convert to a PROJ4 representation.

Returns

str

to_string(self)

Convert to a PROJ4 or WKT string.

The output will be reduced as much as possible by attempting a match to CRS defined in authority files.

Notes

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.

Returns

str

Raises

CRSError

to_wkt(self, morph_to_esri_dialect=False, version=None)

Convert to a OGC WKT representation.

New in version 1.9.0.

Parameters

morph_to_esri_dialectbool, optional

Whether or not to morph to the Esri dialect of WKT Only applies to GDAL versions < 3. This parameter will be removed in a future version of fiona (2.0.0).

versionWktVersion or str, optional

The version of the WKT output. Defaults to GDAL’s default (WKT1_GDAL for GDAL 3).

Returns

str

Raises

CRSError

units_factor

Get units and the conversion factor of the CRS.

Returns

unitsstr

“m”, “ft”, etc.

factorfloat

Ratio of one unit to one radian if the CRS is geographic otherwise, it is to one meter.

Raises

CRSError

values(self)
wkt

An OGC WKT representation of the CRS

Returns

str

fiona.crs.epsg_treats_as_latlong(input_crs)

Test if the CRS is in latlon order

New in version 1.9.0.

From GDAL docs:

> This method returns TRUE if EPSG feels this geographic coordinate system should be treated as having lat/long coordinate ordering.

> Currently this returns TRUE for all geographic coordinate systems with an EPSG code set, and axes set defining it as lat, long.

> FALSE will be returned for all coordinate systems that are not geographic, or that do not have an EPSG code set.

> Note

> Important change of behavior since GDAL 3.0. In previous versions, geographic CRS imported with importFromEPSG() would cause this method to return FALSE on them, whereas now it returns TRUE, since importFromEPSG() is now equivalent to importFromEPSGA().

Parameters

input_crsCRS

Coordinate reference system, as a fiona CRS object Example: CRS({‘init’: ‘EPSG:4326’})

Returns

bool

fiona.crs.epsg_treats_as_northingeasting(input_crs)

Test if the CRS should be treated as having northing/easting coordinate ordering

New in version 1.9.0.

From GDAL docs:

> This method returns TRUE if EPSG feels this projected coordinate system should be treated as having northing/easting coordinate ordering.

> Currently this returns TRUE for all projected coordinate systems with an EPSG code set, and axes set defining it as northing, easting.

> FALSE will be returned for all coordinate systems that are not projected, or that do not have an EPSG code set.

> Note

> Important change of behavior since GDAL 3.0. In previous versions, projected CRS with northing, easting axis order imported with importFromEPSG() would cause this method to return FALSE on them, whereas now it returns TRUE, since importFromEPSG() is now equivalent to importFromEPSGA().

Parameters

input_crsCRS

Coordinate reference system, as a fiona CRS object Example: CRS({‘init’: ‘EPSG:4326’})

Returns

bool

fiona.crs.from_epsg(val)

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

Deprecated since version 1.9.0: This function will be removed in version 2.0. Please use CRS.from_epsg() instead.

fiona.crs.from_string(val)

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

Deprecated since version 1.9.0: This function will be removed in version 2.0. Please use CRS.from_string() instead.

fiona.crs.to_string(val)

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

Deprecated since version 1.9.0: This function will be removed in version 2.0. Please use CRS.to_string() instead.

fiona.drvsupport module

fiona.drvsupport.driver_from_extension(path)

Attempt to auto-detect driver based on the extension.

Parameters

path: str or pathlike object

The path to the dataset to write with.

Returns

str:

The name of the driver for the extension.

fiona.drvsupport.vector_driver_extensions()

Returns

dict:

Map of extensions to the driver.

fiona.env module

Fiona’s GDAL/AWS environment

class fiona.env.Env(session=None, aws_unsigned=False, profile_name=None, session_class=<function Session.aws_or_dummy>, **options)

Bases: object

Abstraction for GDAL and AWS configuration

The GDAL library is stateful: it has a registry of format drivers, an error stack, and dozens of configuration options.

Fiona’s approach to working with GDAL is to wrap all the state up using a Python context manager (see PEP 343, https://www.python.org/dev/peps/pep-0343/). When the context is entered GDAL drivers are registered, error handlers are configured, and configuration options are set. When the context is exited, drivers are removed from the registry and other configurations are removed.

Example:

with fiona.Env(GDAL_CACHEMAX=512) as env:

# All drivers are registered, GDAL’s raster block cache # size is set to 512MB. # Commence processing… … # End of processing.

# At this point, configuration options are set to their # previous (possible unset) values.

A boto3 session or boto3 session constructor arguments aws_access_key_id, aws_secret_access_key, aws_session_token may be passed to Env’s constructor. In the latter case, a session will be created as soon as needed. AWS credentials are configured for GDAL as needed.

credentialize()

Get credentials and configure GDAL

Note well: this method is a no-op if the GDAL environment already has credentials, unless session is not None.

Returns

None

classmethod default_options()

Default configuration options

Parameters

None

Returns

dict

drivers()

Return a mapping of registered drivers.

classmethod from_defaults(*args, **kwargs)

Create an environment with default config options

Parameters

argsoptional

Positional arguments for Env()

kwargsoptional

Keyword arguments for Env()

Returns

Env

Notes

The items in kwargs will be overlaid on the default values.

class fiona.env.GDALVersion(major=0, minor=0)

Bases: object

Convenience class for obtaining GDAL major and minor version components and comparing between versions. This is highly simplistic and assumes a very normal numbering scheme for versions and ignores everything except the major and minor components.

at_least(other)
major
minor
classmethod parse(input)

Parses input tuple or string to GDALVersion. If input is a GDALVersion instance, it is returned.

Parameters

input: tuple of (major, minor), string, or instance of GDALVersion

Returns

GDALVersion instance

classmethod runtime()

Return GDALVersion of current GDAL runtime

class fiona.env.NullContextManager

Bases: object

class fiona.env.ThreadEnv

Bases: _local

fiona.env.defenv(**options)

Create a default environment if necessary.

fiona.env.delenv()

Delete options in the existing environment.

fiona.env.ensure_env(f)

A decorator that ensures an env exists before a function calls any GDAL C functions.

Parameters

ffunction

A function.

Returns

A function wrapper.

Notes

If there is already an existing environment, the wrapper does nothing and immediately calls f with the given arguments.

fiona.env.ensure_env_with_credentials(f)

Ensures a config environment exists and has credentials.

Parameters

ffunction

A function.

Returns

A function wrapper.

Notes

The function wrapper checks the first argument of f and credentializes the environment if the first argument is a URI with scheme “s3”.

If there is already an existing environment, the wrapper does nothing and immediately calls f with the given arguments.

fiona.env.env_ctx_if_needed()

Return an Env if one does not exist

Returns

Env or a do-nothing context manager

fiona.env.getenv()

Get a mapping of current options.

fiona.env.hascreds()
fiona.env.hasenv()
fiona.env.require_gdal_version(version, param=None, values=None, is_max_version=False, reason='')

A decorator that ensures the called function or parameters are supported by the runtime version of GDAL. Raises GDALVersionError if conditions are not met.

Examples: 

@require_gdal_version(‘2.2’) def some_func():

calling some_func with a runtime version of GDAL that is < 2.2 raises a GDALVersionErorr.



@require_gdal_version(‘2.2’, param=’foo’) def some_func(foo=’bar’):

calling some_func with parameter foo of any value on GDAL < 2.2 raises a GDALVersionError.



@require_gdal_version(‘2.2’, param=’foo’, values=(‘bar’,)) def some_func(foo=None):

calling some_func with parameter foo and value bar on GDAL < 2.2 raises a GDALVersionError.

Parameters

version: tuple, string, or GDALVersion param: string (optional, default: None)

If values are absent, then all use of this parameter with a value other than default value requires at least GDAL version.

values: tuple, list, or set (optional, default: None)

contains values that require at least GDAL version. param is required for values.

is_max_version: bool (optional, default: False)

if True indicates that the version provided is the maximum version allowed, instead of requiring at least that version.

reason: string (optional: default: ‘’)

custom error message presented to user in addition to message about GDAL version. Use this to provide an explanation of what changed if necessary context to the user.

Returns

wrapped function

fiona.env.setenv(**options)

Set options in the existing environment.

fiona.errors module

exception fiona.errors.AttributeFilterError

Bases: FionaValueError

Error processing SQL WHERE clause with the dataset.

exception fiona.errors.CRSError

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

Encapsulates unsupported driver and driver mode errors.

exception fiona.errors.DriverIOError

Bases: OSError

A format specific driver error.

exception fiona.errors.DriverSupportError

Bases: DriverIOError

Driver does not support schema

exception fiona.errors.EnvError

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

A warning about deprecation of Fiona features

exception fiona.errors.FionaError

Bases: Exception

Base Fiona error

exception fiona.errors.FionaValueError

Bases: FionaError, ValueError

Fiona-specific value errors

exception fiona.errors.GDALVersionError

Bases: FionaError

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

exception fiona.errors.GeometryTypeValidationError

Bases: FionaValueError

Tried to write a geometry type not specified in the schema

exception fiona.errors.SchemaError

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

Bases: FionaError

Raised if a coordinate transformation fails.

exception fiona.errors.UnsupportedGeometryTypeError

Bases: KeyError

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

exception fiona.errors.UnsupportedOperation

Bases: FionaError

Raised when reading from a file opened in ‘w’ mode

fiona.inspector module

fiona.inspector.main(srcfile)

Open a dataset in an iteractive session.

fiona.io module

Classes capable of reading and writing collections

class fiona.io.MemoryFile(file_or_bytes=None, filename=None, ext='')

Bases: MemoryFileBase

A BytesIO-like object, backed by an in-memory file.

This allows formatted files to be read and written without I/O.

A MemoryFile created with initial bytes becomes immutable. A MemoryFile created without initial bytes may be written to using either file-like or dataset interfaces.

Parameters

file_or_bytesan open Python file, bytes, or None

If not None, the MemoryFile becomes immutable and read-only. If None, it is write-only.

filenamestr

An optional filename. The default is a UUID-based name.

extstr

An optional file extension. Some format drivers require a specific value.

listdir(path=None)

List files in a directory.

Parameters

pathURI (str or pathlib.Path)

A dataset resource identifier.

Returns

list

A list of filename strings.

listlayers(path=None)

List layer names in their index order

Parameters

pathURI (str or pathlib.Path)

A dataset resource identifier.

Returns

list

A list of layer name strings.

open(mode=None, driver=None, schema=None, crs=None, encoding=None, layer=None, vfs=None, enabled_drivers=None, crs_wkt=None, allow_unsupported_drivers=False, **kwargs)

Open the file and return a Fiona collection object.

If data has already been written, the file is opened in ‘r’ mode. Otherwise, the file is opened in ‘w’ mode.

Parameters

Note well that there is no path parameter: a MemoryFile contains a single dataset and there is no need to specify a path.

Other parameters are optional and have the same semantics as the parameters of fiona.open().

class fiona.io.ZipMemoryFile(file_or_bytes=None, filename=None, ext='.zip')

Bases: MemoryFile

A read-only BytesIO-like object backed by an in-memory zip file.

This allows a zip file containing formatted files to be read without I/O.

Parameters

file_or_bytesan open Python file, bytes, or None

If not None, the MemoryFile becomes immutable and read-only. If None, it is write-only.

filenamestr

An optional filename. The default is a UUID-based name.

extstr

An optional file extension. Some format drivers require a specific value. The default is “.zip”.

open(path=None, driver=None, encoding=None, layer=None, enabled_drivers=None, allow_unsupported_drivers=False, **kwargs)

Open a dataset within the zipped stream.

Parameters

pathstr

Path to a dataset in the zip file, relative to the root of the archive.

Returns

A Fiona collection object

fiona.logutils module

Logging helper classes.

class fiona.logutils.FieldSkipLogFilter(name='')

Bases: Filter

Filter field skip log messges.

At most, one message per field skipped per loop will be passed.

filter(record)

Pass record if not seen.

class fiona.logutils.LogFiltering(logger, filter)

Bases: object

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

class fiona.ogrext.Iterator

Bases: object

Provides iterated access to feature data.

class fiona.ogrext.KeysIterator

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

Returns

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

Returns

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

Get a dictionary representation of a collection’s schema.

The schema dict contains “geometry” and “properties” items.

Returns

dict

Warnings

Fiona 1.9 does not support multiple fields with the name name. When encountered, a warning message is logged and the field is skipped.

get_tag_item()

Returns tag item value

Parameters

key: str

The key for the metadata item to fetch.

ns: str, optional

Used to select a namespace other than the default.

Returns

str

has_feature()

Provides access to feature data by FID.

Supports Collection.__contains__().

isactive()
start()
stop()
tags()

Returns a dict containing copies of the dataset or layers’s tags. Tags are pairs of key and value strings. Tags belong to namespaces. The standard namespaces are: default (None) and ‘IMAGE_STRUCTURE’. Applications can create their own additional namespaces.

Parameters

ns: str, optional

Can be used to select a namespace other than the default.

Returns

dict

class fiona.ogrext.TZ(minutes)

Bases: tzinfo

utcoffset(dt)

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

class fiona.ogrext.WritingSession

Bases: Session

start()
sync()

Syncs OGR to disk.

update_tag_item()

Updates the tag item value

Parameters

key: str

The key for the metadata item to set.

tag: str

The value of the metadata item to set.

ns: str

Used to select a namespace other than the default.

Returns

int

update_tags()

Writes a dict containing the dataset or layers’s tags. Tags are pairs of key and value strings. Tags belong to namespaces. The standard namespaces are: default (None) and ‘IMAGE_STRUCTURE’. Applications can create their own additional namespaces.

Parameters

tags: dict

The dict of metadata items to set.

ns: str, optional

Used to select a namespace other than the default.

Returns

int

writerecs()

Writes records to collection storage.

Parameters

recordsIterable

A stream of feature records.

collectionCollection

The collection in which feature records are stored.

Returns

None

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.path module

Dataset paths, identifiers, and filenames

class fiona.path.ParsedPath(path, archive, scheme)

Bases: Path

Result of parsing a dataset URI/Path

Attributes

pathstr

Parsed path. Includes the hostname and query string in the case of a URI.

archivestr

Parsed archive path.

schemestr

URI scheme such as “https” or “zip+s3”.

archive
classmethod from_uri(uri)
property is_local

Test if the path is a local URI

property is_remote

Test if the path is a remote, network URI

property name

The parsed path’s original URI

path
scheme
class fiona.path.Path

Bases: object

Base class for dataset paths

class fiona.path.UnparsedPath(path)

Bases: Path

Encapsulates legacy GDAL filenames

Attributes

pathstr

The legacy GDAL filename.

property name

The unparsed path’s original path

path
fiona.path.parse_path(path)

Parse a dataset’s identifier or path into its parts

Parameters

pathstr or path-like object

The path to be parsed.

Returns

ParsedPath or UnparsedPath

Notes

When legacy GDAL filenames are encountered, they will be returned in a UnparsedPath.

fiona.path.vsi_path(path)

Convert a parsed path to a GDAL VSI path

Parameters

pathPath

A ParsedPath or UnparsedPath object.

Returns

str

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

Parameters

text: string to be parsed

Returns

(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

Parameters

text: string to be parsed

Returns

(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

Parameters

text: string to be parsed

Returns

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

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

fiona.schema module

Fiona schema module.

fiona.schema.normalize_field_type()

Normalize free form field types to an element of FIELD_TYPES

Parameters

ftypestr

A type:width format like ‘int:9’ or ‘str:255’

Returns

str

An element from FIELD_TYPES

fiona.session module

Abstraction for sessions in various clouds.

class fiona.session.AWSSession(session=None, aws_unsigned=False, aws_access_key_id=None, aws_secret_access_key=None, aws_session_token=None, region_name=None, profile_name=None, endpoint_url=None, requester_pays=False)

Bases: Session

Configures access to secured resources stored in AWS S3.

property credentials

The session credentials as a dict

get_credential_options()

Get credentials as GDAL configuration options

Returns

dict

classmethod hascreds(config)

Determine if the given configuration has proper credentials

Parameters

clsclass

A Session class.

configdict

GDAL configuration as a dict.

Returns

bool

class fiona.session.AzureSession(azure_storage_connection_string=None, azure_storage_account=None, azure_storage_access_key=None, azure_unsigned=False)

Bases: Session

Configures access to secured resources stored in Microsoft Azure Blob Storage.

property credentials

The session credentials as a dict

get_credential_options()

Get credentials as GDAL configuration options

Returns

dict

classmethod hascreds(config)

Determine if the given configuration has proper credentials

Parameters

clsclass

A Session class.

configdict

GDAL configuration as a dict.

Returns

bool

class fiona.session.DummySession(*args, **kwargs)

Bases: Session

A dummy session.

Attributes

credentialsdict

The session credentials.

get_credential_options()

Get credentials as GDAL configuration options

Returns

dict

classmethod hascreds(config)

Determine if the given configuration has proper credentials

Parameters

clsclass

A Session class.

configdict

GDAL configuration as a dict.

Returns

bool

class fiona.session.GSSession(google_application_credentials=None)

Bases: Session

Configures access to secured resources stored in Google Cloud Storage

property credentials

The session credentials as a dict

get_credential_options()

Get credentials as GDAL configuration options

Returns

dict

classmethod hascreds(config)

Determine if the given configuration has proper credentials

Parameters

clsclass

A Session class.

configdict

GDAL configuration as a dict.

Returns

bool

class fiona.session.OSSSession(oss_access_key_id=None, oss_secret_access_key=None, oss_endpoint=None)

Bases: Session

Configures access to secured resources stored in Alibaba Cloud OSS.

property credentials

The session credentials as a dict

get_credential_options()

Get credentials as GDAL configuration options

Returns

dict

classmethod hascreds(config)

Determine if the given configuration has proper credentials

Parameters

clsclass

A Session class.

configdict

GDAL configuration as a dict.

Returns

bool

class fiona.session.Session

Bases: object

Base for classes that configure access to secured resources.

Attributes

credentialsdict

Keys and values for session credentials.

Notes

This class is not intended to be instantiated.

static aws_or_dummy(*args, **kwargs)

Create an AWSSession if boto3 is available, else DummySession Parameters ———- path : str

A dataset path or identifier.

argssequence

Positional arguments for the foreign session constructor.

kwargsdict

Keyword arguments for the foreign session constructor.

Returns

Session

static cls_from_path(path)

Find the session class suited to the data at path.

Parameters

pathstr

A dataset path or identifier.

Returns

class

static from_environ(*args, **kwargs)

Create a session object suited to the environment. Parameters ———- path : str

A dataset path or identifier.

argssequence

Positional arguments for the foreign session constructor.

kwargsdict

Keyword arguments for the foreign session constructor.

Returns

Session

static from_foreign_session(session, cls=None)

Create a session object matching the foreign session.

Parameters

sessionobj

A foreign session object.

clsSession class, optional

The class to return.

Returns

Session

static from_path(path, *args, **kwargs)

Create a session object suited to the data at path.

Parameters

pathstr

A dataset path or identifier.

argssequence

Positional arguments for the foreign session constructor.

kwargsdict

Keyword arguments for the foreign session constructor.

Returns

Session

get_credential_options()

Get credentials as GDAL configuration options

Returns

dict

classmethod hascreds(config)

Determine if the given configuration has proper credentials

Parameters

clsclass

A Session class.

configdict

GDAL configuration as a dict.

Returns

bool

class fiona.session.SwiftSession(session=None, swift_storage_url=None, swift_auth_token=None, swift_auth_v1_url=None, swift_user=None, swift_key=None)

Bases: Session

Configures access to secured resources stored in OpenStack Swift Object Storage.

property credentials

The session credentials as a dict

get_credential_options()

Get credentials as GDAL configuration options

Returns

dict

classmethod hascreds(config)

Determine if the given configuration has proper credentials

Parameters

clsclass

A Session class.

configdict

GDAL configuration as a dict.

Returns

bool

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.

Parameters

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.

Returns

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.

Examples

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

Parameters

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 or an iterable of GeoJSON-like geometry objects.

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

Round geometry coordinates to this number of decimal places. This parameter is deprecated and will be removed in 2.0.

Returns

obj

A new GeoJSON-like geometry (or a list of GeoJSON-like geometries if an iterable was given as input) 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.

Examples

>>> transform_geom(
...     'EPSG:4326', 'EPSG:26953',
...     {'type': 'Point', 'coordinates': [-105.0, 40.0]})
{'type': 'Point', 'coordinates': (957097.0952383667, 378940.8419189212)}

fiona.vfs module

Implementation of Apache VFS schemes and URLs.

fiona.vfs.is_remote(scheme)
fiona.vfs.parse_paths(uri, vfs=None)

Parse a URI or Apache VFS URL into its parts

Returns: tuple

(path, scheme, archive)

fiona.vfs.valid_vsi(vsi)

Ensures all parts of our vsi path are valid schemes.

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

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’: ‘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.

class fiona.Feature(geometry=None, id=None, properties=None, **data)

Bases: Object

A GeoJSON-like feature

Notes

Delegates geometry and properties to an instance of _Feature, which will become an extension class in Fiona 2.0.

classmethod from_dict(ob=None, **kwargs)
property geometry

The feature’s geometry object

Returns

Geometry

property id

The feature’s id

Returns

object

property properties

The feature’s properties

Returns

object

property type

The Feature’s type

Returns

str

class fiona.Geometry(coordinates=None, type=None, geometries=None, **data)

Bases: Object

A GeoJSON-like geometry

Notes

Delegates coordinates and type properties to an instance of _Geometry, which will become an extension class in Fiona 2.0.

property coordinates

The geometry’s coordinates

Returns

Sequence

classmethod from_dict(ob=None, **kwargs)
property geometries

A collection’s geometries.

Returns

list

property type

The geometry’s type

Returns

str

class fiona.Properties(**kwds)

Bases: Object

A GeoJSON-like feature’s properties

classmethod from_dict(mapping=None, **kwargs)
fiona.bounds(ob)

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

The ob may be a feature record or geometry.

fiona.listdir(path)

List files in a directory Parameters ———- path : URI (str or pathlib.Path)

A dataset resource identifier.

Returns

list

A list of filename strings.

fiona.listlayers(fp, vfs=None, **kwargs)

List layer names in their index order

Parameters

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.

kwargsdict

Dataset opening options and other keyword args.

Returns

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, allow_unsupported_drivers=False, **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’])

Parameters

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.

ignore_fieldslist

List of field names to ignore on load.

ignore_geometrybool

Ignore the geometry on load.

include_fieldslist

List of a subset of field names to include on load.

wkt_versionfiona.enums.WktVersion or str, optional

Version to use to for the CRS WKT. Defaults to GDAL’s default (WKT1_GDAL for GDAL 3).

allow_unsupported_driversbool

If set to true do not limit GDAL drivers to set set of known working.

kwargsmapping

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

Returns

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