1

The following piece of code returns a shp following the driver and crs of a model .shp.

import numpy as np #just to test I correctly handle data types
import fiona
from shapely.geometry import Polygon, mapping
with fiona.open('model.shp') as source:
    source_driver = source.driver
    source_crs = source.crs
    #source_schema = source.schema
    source_schema = {'geometry': 'Polygon',
                 'properties': {'field_name': 'float'}} #Beware: field names cannot be longer than 10 characters!
        #writing a new file    
            with fiona.open('output.shp',
                            'w',
                             driver=source_driver,
                             crs=source_crs,
                             schema=source_schema) as collection:
                rec = {}
                rec['geometry'] = mapping(Polygon([(0,0),(1,0),(1,1),(0,0)]))
                rec['properties'] = {'field_name': float(np.float(0.3))}
                collection.write(rec)

The written record can be checked in this way:

collection = fiona.open('output.shp')
rec = collection.next()
print rec

Which returns: {'geometry': {'type': 'Polygon', 'coordinates': [[(0.0, 0.0), (1.0, 1.0), (1.0, 0.0), (0.0, 0.0)]]}, 'type': 'Feature', 'id': '0', 'properties': OrderedDict([(u'field_name', 0.3)])}

I followed @genes' hints from this post and @sgillies' recommendations below.

Jaqo
  • 153
  • 1
  • 10
  • This code works on Fiona 1.2.0. It does not in 1.1.4. Have a look at @sgillies' answer below and respective comments. – Jaqo Oct 22 '14 at 09:08

1 Answers1

2

Shapefile fields are constrained to 10 chars, and so your 'a_fieldname' gets truncated by OGR (used by Fiona) to 'a_fieldname'. There might be a Fiona bug here. Workaround in the meanwhile is to change 'a_fieldname' in your schema to 'number' or something shorter than 10.

sgillies
  • 9,056
  • 1
  • 33
  • 41
  • 1
    I'm unable to reproduce the problem. See https://github.com/Toblerity/Fiona/issues/177. I don't know what version you're using, but 1.1.4 (2014-04-03) fixed a possibly related bug. – sgillies Oct 21 '14 at 20:21
  • thanks for your help. The name extend was indeed the problem. I was using Fiona 1.0.3 version. I updated to 1.2.0. Now, when I run the posted code, I receive a report about the truncation: WARNING:Fiona:OGR Error 6: Normalized/laundered field name: 'a_fieldname' to 'a_fieldnam'; and my field properly receives the intended float value. Also thank you for Fiona and Shapely. They rock! – Jaqo Oct 22 '14 at 08:02