[FWTools] edit shapefile attributes with Python

Ken Boss Ken.Boss at dnr.state.mn.us
Tue Aug 15 16:48:38 EDT 2006


Bryan--

I believe you may need to:

dsRiver.Destroy()

after your edits in order to get them written out to disk.

HTH,

--Ken

>>> Bryan Keith <bryan at geomega.com> 8/15/2006 3:36:37 PM >>>
Frank Warmerdam wrote:
> Bryan Keith wrote:
>> Hello,
>>
>> I'm simply trying to edit the attributes of a shapefile with Python.
 I 
>> have no trouble creating a new shapefile, creating new features, and

>> adding them to the shapefile.  However, now I just want to edit 
>> attributes of the dbf.   Here's my simple script:
>>
>> import ogr
>> #get the stream
>> ogrdriver = ogr.GetDriverByName("ESRI Shapefile")
>> dsRiver = ogrdriver.Open("test_py.shp")
>> mRiverLayer = dsRiver.GetLayerByName("test_py")
>> mFeature = mRiverLayer.GetFeature(0)
>> iIndex = mFeature.GetFieldIndex("RIVER_MILE")
>> mFeature.SetField(iIndex, 100.1)
>> mRiverLayer.SetFeature(mFeature)
>>
>> which gives me this error:
>>
>> ERROR 3: Error in fseek() or fwrite() writing object to .shp file.
>>
>> Is attribute updating supported in shapefiles?  What am I doing
wrong? 
>> Thanks for the help.
> 
> Brian,
> 
> I'm not sure if this got answered already or not.
> Try opening the file in update mode.
> 
> eg.
> 
>   import ogr
>  > #get the stream
>  > ogrdriver = ogr.GetDriverByName("ESRI Shapefile")
>  > dsRiver = ogrdriver.Open("test_py.shp",1)
> 

Frank,

Thanks.  That's one of the things that I tried after posting my
message. 
  It doesn't help, however.  I no longer get the error message.  The 
.shp file has a new timestep, but the .dbf doesn't, and the attribute 
didn't change.

Here's the simple code, and the ogrinfo output after running the code:

import ogr
ogrdriver = ogr.GetDriverByName("ESRI Shapefile")
dsRiver = ogrdriver.Open("test_py.shp", 1)
mRiverLayer = dsRiver.GetLayerByName("test_py")
mFeature = mRiverLayer.GetFeature(0)
iIndex = mFeature.GetFieldIndex("RIVER_MILE")
mFeature.SetField(iIndex, 100.1)
mRiverLayer.SetFeature(mFeature)

ogrinfo -sql "select RIVER_MILE from test_py" test_py.shp -al
INFO: Open of `test_py.shp'
       using driver `ESRI Shapefile' successful.

Layer name: test_py
Geometry: Polygon
Feature Count: 1
Extent: (492238.723643, 664969.987499) - (526881.068923,
692475.373737)
Layer SRS WKT:
(unknown)
RIVER_MILE: Real (10.3)
OGRFeature(test_py):0
   RIVER_MILE (Real) =   -999.900

I also tried enclosing the edit in .StartTransaction() and 
.CommitTransaction(), and I tried .SyncToDisk(), but those didn't
help.

Bryan
_______________________________________________
FWTools mailing list
FWTools at lists.maptools.org 
http://lists.maptools.org/mailman/listinfo/fwtools 
http://fwtools.maptools.org/


More information about the FWTools mailing list