1

How to set the CRS when writing an ESRI Shapefile using Fiona on a modern Python version (>3.x)?

Why "modern"? Because Python 2 is now deprecated and this user asked a similar question for Python 2.7, which received (now probably) old fashioned answers: Fiona fails to write CRS to shapefile

1

This should work out of the box with fiona.__version__ : '1.8.20' (Python 3.6.9):

import fiona
from shapely.geometry import Point, mapping

my_schema = {
    'geometry': 'Point',
    'properties': {
        'id': 'int',
        'attribute1': 'float'},
}

my_id = 1
a_shapely_point = Point(9.17044, 45.45340)

with fiona.open('/path/to/shapefile.shp',
                mode='w',
                driver='ESRI Shapefile', 
                crs='epsg:4326', # <-------- Set CRS here using EPSG code!
                schema=my_schema) as c:
    c.write(
        {
            'geometry': mapping(a_shapely_point),
            'properties': {'id': my_id, 'attribute1': 3.1415},
        }
    )

You can then check it has been correctly written with ogrinfo for example:

$ cd /path/to
$ ogrinfo -so -ro -al shapefile.shp 

INFO: Open of `shapefile.shp'
      using driver `ESRI Shapefile' successful.

Layer name: test
Metadata:
  DBF_DATE_LAST_UPDATE=2021-07-14
Geometry: Point
Feature Count: 1
Extent: (9.170440, 45.453400) - (9.170440, 45.453400)
Layer SRS WKT:
GEOGCRS["WGS 84",
    DATUM["World Geodetic System 1984",
        ELLIPSOID["WGS 84",6378137,298.257223563,
            LENGTHUNIT["metre",1]]],
    PRIMEM["Greenwich",0,
        ANGLEUNIT["degree",0.0174532925199433]],
    CS[ellipsoidal,2],
        AXIS["latitude",north,
            ORDER[1],
            ANGLEUNIT["degree",0.0174532925199433]],
        AXIS["longitude",east,
            ORDER[2],
            ANGLEUNIT["degree",0.0174532925199433]],
    ID["EPSG",4326]]
Data axis to CRS axis mapping: 2,1
id: Integer64 (18.0)
attribute1: Real (24.15)

It also loads flawlessly in QGIS.

Doc on fiona.open(): https://fiona.readthedocs.io/en/latest/fiona.html#fiona.open

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.