Convert Figma logo to code with AI

Toblerity logoFiona

Fiona reads and writes geographic data files

1,145
202
1,145
30

Top Related Projects

Python tools for geographic data

Documentation and samples for ArcGIS API for Python

1,040

Python interface to PROJ (cartographic projections and coordinate transformations library)

3,831

Manipulation and analysis of geometric objects

Rasterio reads and writes geospatial raster datasets

4,773

GDAL is an open source MIT licensed translator library for raster and vector geospatial data formats.

Quick Overview

Fiona is a Python library for reading and writing geospatial data files. It provides a high-level interface for working with vector data formats such as Shapefiles, GeoJSON, and others supported by the GDAL library. Fiona simplifies the process of handling geospatial data in Python, making it easier for developers and data scientists to work with geographic information.

Pros

  • Easy-to-use Pythonic interface for working with geospatial data
  • Supports a wide range of vector data formats through GDAL
  • Integrates well with other geospatial libraries in the Python ecosystem
  • Efficient handling of large datasets

Cons

  • Limited support for raster data formats
  • Requires GDAL to be installed, which can be challenging on some systems
  • Learning curve for users new to geospatial concepts
  • Performance may be slower compared to lower-level GDAL bindings for some operations

Code Examples

Reading a shapefile:

import fiona

with fiona.open('path/to/shapefile.shp', 'r') as src:
    for feature in src:
        print(feature['properties'])

Writing a GeoJSON file:

import fiona
from fiona.crs import from_epsg

schema = {
    'geometry': 'Point',
    'properties': {'name': 'str', 'value': 'int'}
}

with fiona.open('output.geojson', 'w', 
                driver='GeoJSON', 
                crs=from_epsg(4326), 
                schema=schema) as dst:
    dst.write({
        'geometry': {'type': 'Point', 'coordinates': (0, 0)},
        'properties': {'name': 'Example', 'value': 42}
    })

Reprojecting features:

import fiona
from fiona.transform import transform_geom

with fiona.open('input.shp', 'r') as src:
    with fiona.open('output.shp', 'w', 
                    driver=src.driver, 
                    crs='EPSG:3857', 
                    schema=src.schema) as dst:
        for feature in src:
            feature['geometry'] = transform_geom(
                src.crs, 'EPSG:3857', feature['geometry']
            )
            dst.write(feature)

Getting Started

To get started with Fiona, first install it using pip:

pip install fiona

Then, you can import and use Fiona in your Python scripts:

import fiona

# Open a shapefile
with fiona.open('path/to/shapefile.shp', 'r') as src:
    # Print the coordinate reference system (CRS)
    print(src.crs)
    
    # Print the schema of the shapefile
    print(src.schema)
    
    # Iterate through features
    for feature in src:
        print(feature['geometry']['type'])
        print(feature['properties'])

This example opens a shapefile, prints its CRS and schema, and then iterates through the features, printing the geometry type and properties of each feature.

Competitor Comparisons

Python tools for geographic data

Pros of GeoPandas

  • Integrates seamlessly with pandas, providing a familiar DataFrame-like interface for geospatial data
  • Offers high-level geospatial operations and analysis tools out of the box
  • Supports visualization of geospatial data with built-in plotting capabilities

Cons of GeoPandas

  • Can be slower for large datasets compared to Fiona's lower-level approach
  • Has more dependencies, which can make installation and management more complex
  • May have a steeper learning curve for users not familiar with pandas

Code Comparison

GeoPandas:

import geopandas as gpd

gdf = gpd.read_file("data.shp")
gdf['area'] = gdf.geometry.area
gdf.plot()

Fiona:

import fiona

with fiona.open("data.shp", "r") as source:
    for feature in source:
        # Process each feature individually
        pass

GeoPandas provides a higher-level interface with built-in analysis and visualization tools, while Fiona offers lower-level access to geospatial data, requiring more manual processing but potentially offering better performance for large datasets.

Documentation and samples for ArcGIS API for Python

Pros of arcgis-python-api

  • Comprehensive integration with ArcGIS ecosystem and services
  • Rich set of GIS analysis and visualization tools
  • Supports both online and enterprise ArcGIS environments

Cons of arcgis-python-api

  • Requires ArcGIS license for full functionality
  • Steeper learning curve due to complex API structure
  • Limited support for non-Esri data formats and services

Code Comparison

Fiona example:

import fiona

with fiona.open('data.shp', 'r') as source:
    for feature in source:
        # Process each feature

arcgis-python-api example:

from arcgis.gis import GIS
from arcgis.features import FeatureLayer

gis = GIS()
layer = FeatureLayer('feature_layer_url')
for feature in layer.query():
    # Process each feature

Both libraries provide ways to work with geospatial data, but Fiona focuses on reading and writing various formats, while arcgis-python-api offers a broader range of GIS functionality within the ArcGIS ecosystem. Fiona is more lightweight and suitable for simple I/O operations, whereas arcgis-python-api is better for complex GIS tasks and integration with ArcGIS services.

1,040

Python interface to PROJ (cartographic projections and coordinate transformations library)

Pros of pyproj

  • Specialized in coordinate transformations and geodetic calculations
  • Supports a wide range of projection systems and datums
  • Integrates well with other geospatial libraries like GeoPandas and Shapely

Cons of pyproj

  • Focused primarily on coordinate operations, lacking broader GIS functionality
  • May have a steeper learning curve for users new to geodetic concepts

Code Comparison

pyproj example:

from pyproj import Transformer

transformer = Transformer.from_crs("EPSG:4326", "EPSG:3857")
x, y = transformer.transform(51.5074, -0.1278)

Fiona example:

import fiona

with fiona.open('input.shp') as source:
    schema = source.schema.copy()
    with fiona.open('output.shp', 'w', crs='EPSG:3857', **source.meta) as sink:
        for feature in source:
            sink.write(feature)

Summary

pyproj excels in coordinate transformations and geodetic calculations, offering extensive support for various projection systems. It integrates well with other geospatial libraries but may have a steeper learning curve.

Fiona, on the other hand, provides a more comprehensive set of GIS functionalities, including reading and writing various geospatial file formats. It offers a simpler interface for general GIS operations but may not be as specialized in coordinate transformations as pyproj.

The choice between the two depends on the specific requirements of your geospatial project and the level of specialization needed in coordinate operations versus general GIS functionality.

3,831

Manipulation and analysis of geometric objects

Pros of Shapely

  • Focuses on geometric operations and manipulations
  • Provides a rich set of geometric functions and predicates
  • Supports various geometric types (points, lines, polygons)

Cons of Shapely

  • Limited support for reading/writing geospatial data formats
  • Lacks direct integration with GIS data sources
  • May require additional libraries for complex geospatial tasks

Code Comparison

Shapely example:

from shapely.geometry import Point, Polygon

point = Point(0, 0)
polygon = Polygon([(0, 0), (1, 1), (1, 0)])
print(polygon.contains(point))

Fiona example:

import fiona

with fiona.open('data.shp', 'r') as source:
    for feature in source:
        print(feature['geometry'])

Shapely focuses on geometric operations, while Fiona specializes in reading and writing geospatial data formats. Shapely is ideal for geometric calculations and manipulations, whereas Fiona excels at handling various GIS file formats and data sources. Users often combine both libraries for comprehensive geospatial data processing workflows.

Rasterio reads and writes geospatial raster datasets

Pros of rasterio

  • Specialized for raster data processing, offering optimized performance for large datasets
  • Provides advanced raster operations like reprojection, resampling, and warping
  • Integrates well with NumPy arrays, allowing for efficient numerical operations

Cons of rasterio

  • Limited functionality for vector data handling compared to Fiona
  • Steeper learning curve for users not familiar with raster data concepts
  • May require additional libraries for certain operations (e.g., GDAL)

Code Comparison

Fiona (vector data):

import fiona

with fiona.open('shapefile.shp', 'r') as src:
    for feature in src:
        # Process vector features

rasterio (raster data):

import rasterio

with rasterio.open('raster.tif') as src:
    data = src.read()
    # Process raster data

Both libraries provide Pythonic interfaces for geospatial data, but they focus on different data types. Fiona is primarily used for vector data (e.g., shapefiles), while rasterio specializes in raster data (e.g., GeoTIFFs). The choice between them depends on the specific data type and processing requirements of your project.

4,773

GDAL is an open source MIT licensed translator library for raster and vector geospatial data formats.

Pros of GDAL

  • More comprehensive and feature-rich, supporting a wider range of geospatial data formats and operations
  • Better performance for large-scale data processing and analysis
  • Extensive documentation and a larger community for support

Cons of GDAL

  • Steeper learning curve due to its complexity and extensive API
  • Heavier and more resource-intensive, which may be overkill for simpler tasks
  • Installation can be more challenging, especially on certain platforms

Code Comparison

GDAL example:

from osgeo import gdal

dataset = gdal.Open("example.tif")
band = dataset.GetRasterBand(1)
data = band.ReadAsArray()

Fiona example:

import fiona

with fiona.open("example.shp", "r") as source:
    for feature in source:
        # Process each feature
        pass

Fiona is more Pythonic and easier to use for simple vector data operations, while GDAL offers more powerful and versatile functionality for both raster and vector data processing. GDAL is better suited for complex geospatial tasks, while Fiona excels in simplicity and ease of use for working with vector data formats.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

===== Fiona

.. image:: https://github.com/Toblerity/Fiona/actions/workflows/tests.yml/badge.svg :target: https://github.com/Toblerity/Fiona/actions/workflows/tests.yml .. image:: https://github.com/Toblerity/Fiona/actions/workflows/test_gdal_latest.yml/badge.svg :target: https://github.com/Toblerity/Fiona/actions/workflows/test_gdal_latest.yml .. image:: https://img.shields.io/pypi/v/fiona :target: https://pypi.org/project/fiona/ .. image:: https://api.securityscorecards.dev/projects/github.com/Toblerity/Fiona/badge :target: https://securityscorecards.dev/viewer/?uri=github.com/Toblerity/Fiona

Fiona streams simple feature data to and from GIS formats like GeoPackage and Shapefile.

Fiona can read and write real-world data using multi-layered GIS formats, zipped and in-memory virtual file systems, from files on your hard drive or in cloud storage. This project includes Python modules and a command line interface (CLI).

Fiona depends on GDAL <https://gdal.org>__ but is different from GDAL's own bindings <https://gdal.org/api/python_bindings.html>__. Fiona is designed to be highly productive and to make it easy to write code which is easy to read.

Installation

Fiona has several extension modules <https://docs.python.org/3/extending/extending.html>__ which link against libgdal. This complicates installation. Binary distributions (wheels) containing libgdal and its own dependencies are available from the Python Package Index and can be installed using pip.

.. code-block:: console

pip install fiona

These wheels are mainly intended to make installation easy for simple applications, not so much for production. They are not tested for compatibility with all other binary wheels, conda packages, or QGIS, and omit many of GDAL's optional format drivers. If you need, for example, GML support you will need to build and install Fiona from a source distribution. It is possible to install Fiona from source using pip (version >= 22.3) and the --no-binary option. A specific GDAL installation can be selected by setting the GDAL_CONFIG environment variable.

.. code-block:: console

pip install -U pip
pip install --no-binary fiona fiona

Many users find Anaconda and conda-forge a good way to install Fiona and get access to more optional format drivers (like GML).

Fiona 1.10 requires Python 3.8 or higher and GDAL 3.4 or higher.

Python Usage

Features are read from and written to file-like Collection objects returned from the fiona.open() function. Features are data classes modeled on the GeoJSON format. They don't have any spatial methods of their own, so if you want to transform them you will need Shapely or something like it. Here is an example of using Fiona to read some features from one data file, change their geometry attributes using Shapely, and write them to a new data file.

.. code-block:: python

import fiona
from fiona import Feature, Geometry
from shapely.geometry import mapping, shape

# Open a file for reading. We'll call this the source.
with fiona.open(
    "zip+https://github.com/Toblerity/Fiona/files/11151652/coutwildrnp.zip"
) as src:

    # The file we'll write to must be initialized with a coordinate
    # system, a format driver name, and a record schema. We can get
    # initial values from the open source's profile property and then
    # modify them as we need.
    profile = src.profile
    profile["schema"]["geometry"] = "Point"
    profile["driver"] = "GPKG"

    # Open an output file, using the same format driver and coordinate
    # reference system as the source. The profile mapping fills in the
    # keyword parameters of fiona.open.
    with fiona.open("centroids.gpkg", "w", **profile) as dst:

        # Process only the feature records intersecting a box.
        for feat in src.filter(bbox=(-107.0, 37.0, -105.0, 39.0)):

            # Get the feature's centroid.
            centroid_shp = shape(feat.geometry).centroid
            new_geom = Geometry.from_dict(centroid_shp)

            # Write the feature out.
            dst.write(
                Feature(geometry=new_geom, properties=f.properties)
            )

    # The destination's contents are flushed to disk and the file is
    # closed when its with block ends. This effectively
    # executes ``dst.flush(); dst.close()``.

CLI Usage

Fiona's command line interface, named "fio", is documented at docs/cli.rst <https://github.com/Toblerity/Fiona/blob/main/docs/cli.rst>__. The CLI has a number of different commands. Its fio cat command streams GeoJSON features from any dataset.

.. code-block:: console

$ fio cat --compact tests/data/coutwildrnp.shp | jq -c '.'
{"geometry":{"coordinates":[[[-111.73527526855469,41.995094299316406],...]]}}
...

Documentation

For more details about this project, please see:

  • Fiona home page <https://github.com/Toblerity/Fiona>__
  • Docs and manual <https://fiona.readthedocs.io/>__
  • Examples <https://github.com/Toblerity/Fiona/tree/main/examples>__
  • Main user discussion group <https://fiona.groups.io/g/main>__
  • Developers discussion group <https://fiona.groups.io/g/dev>__