[gdal-dev] issue updating shapefile using python bindings

Even Rouault even.rouault at spatialys.com
Sat Apr 22 09:52:34 PDT 2017


On samedi 22 avril 2017 09:24:22 CEST Mike wrote:
> Hi -
> I have a script which at one point adds fields to a shapefile, then at
> another time updates those fields. This happens a couple times through this
> whole process.
> 
> #earlier
> 
> driver = ogr.GetDriverByName('ESRI Shapefile')
> 
> dataSource = driver.Open(inshp, 1)
> 
> layer = dataSource.GetLayer()
> 
>     idfield = ogr.FieldDefn('INFLD', ogr.OFTInteger)
> 
>     layer.CreateField(idfield)
> 
> dataSource = None
> 
> 
> 
> #later
> 
> driver = ogr.GetDriverByName('ESRI Shapefile')
> 
> dataSource = driver.Open(inshp, 1)
> 
> layer = dataSource.GetLayer()
> 
> layerDefinition = layer.GetLayerDefn()
> 
> flds = [layerDefinition.GetFieldDefn(i).GetName()
> 
>         for i in range(layerDefinition.GetFieldCount())]
> 
> for feature in layer:
> 
>     for fld in flds:
> 
>         ...
> 
>         print fld,somevalue,type(somevalue) # --> INFLD -9 <type 'int'>
> 
>         feature.SetField(fld,somevalue) # produces error (see below)
> 
>     layer.SetFeature(feature)
> 
>     feature = None
> 
> dataSource = None
> 
> 
> 
> This is the error I get. All of this (later part) is inside a function.
> However when I run the function in IDLE, it works.
> 
> 
>     feature.SetField(fld, somevalue)
> 
>   File
> "C:\PROGRA~1\QGIS2~1.18\apps\Python27\lib\site-packages\osgeo\ogr.py", line
> 4273, in SetField
> 
>     return _ogr.Feature_SetFieldInteger64(self, fld_index, args[1])
> 
> TypeError: in method 'Feature_SetFieldInteger64', argument 2 of type 'int'
> 
> 
> This is what ogrinfo reports on that field..
> 
> ogrinfo -so INSHP.shp
> 
> INFLD: Integer (9.0)
> 
> 
> It seems that it won't take the integer of -9 into the field.
> 
> 
> So, I am fairly new at using the ogr bindings.
> 
> My thoughts are
> 
> 1) Am I closing the shapefile properly from the earlier step?
> 
> 2) Looking at ogr.py 4273, it seems that there is a field type
> difference 'Feature_SetFieldInteger64'
> vs regular int.
> 
> 
> Any pointers on how to move past this would be good. I won't be able to
> look at the error till Monday, so I might not be able to answer any follow
> up questions till then.

I'm not sure if it is your issue, but I could reproduce the same exception when the field name 
is a Python2 unicode string.
The workaround is to convert it to a standard string for example with str(x) if it is an ASCII 
string, or if it can have non ASCII characters with x.encode('utf8')
In 2.2, I've just fixed the bindings to accept a unicode string, in addition to a regular string.

Even


-- 
Spatialys - Geospatial professional services
http://www.spatialys.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.osgeo.org/pipermail/gdal-dev/attachments/20170422/53dc1740/attachment.html>


More information about the gdal-dev mailing list