FW: [gdal-dev] Shapefile read/write

Frank Warmerdam warmerdam at pobox.com
Tue Dec 4 11:26:02 EST 2007


Mullins, Steven wrote:
> Frank,
> 
> Thanks for the reply.  It runs without an error, but is not updating the shapefile on disk.  My Python code is below.  Perhaps I am not opening the file correctly.  I can't find any good example to go by.  Every example I found copies the schema and data to a new file using recursion over the fields.  I also found an old list email (2005) that stated that shapefile write-backs did not work in OGR at that time.  A shapefile write-back would be ideal for me, if It can be done.  Do any errors jump out at you?
> 
> Thanks,
> 
> Steve
> 
> ###############################################
> #!/usr/local/bin/python
> # read SHP file and update attributes per coordinates
> 
> import ogr
> import osr
> import string
> 
> ###############################################
> # Data Source
> data_source = ogr.Open('./shapefiles83/rainfalls-active/rainfalls-active.shp')

Steven,

Thi is your first problem.  You need to open the file in update
mode.  Try:

data_source = ogr.Open('./shapefiles83/rainfalls-active/rainfalls-active.shp',1)

But also the following never actually sends the modified feature
back to the layer.

 > while current_feature is not None:
 >     current_point = current_feature.GetGeometryRef()
 >     current_feature.SetField ( 0, current_point.GetX())
 >     current_feature.SetField ( 1, current_point.GetY())
 >     current_feature = layer_0.GetNextFeature()
 > layer_0.SyncToDisk()
 > data_source.Destroy()

Try adding:

       layer.SetFeature( current_feature )

after the two SetField calls.  The SetFeature() call tells the
layer to write this feature back to disk.  It is often unclear to
people, but the feature object is not a direct proxy for the data
in the datastore.  It is a relatively freestanding feature in
memory that you can manipulate and use.  If you want changes to it
to be reflected in the file, then you need to explicitly request it.

Best regards,
-- 
---------------------------------------+--------------------------------------
I set the clouds in motion - turn up   | Frank Warmerdam, warmerdam at pobox.com
light and sound - activate the windows | http://pobox.com/~warmerdam
and watch the world go round - Rush    | President OSGeo, http://osgeo.org



More information about the gdal-dev mailing list