FW: [gdal-dev] Shapefile read/write

Mullins, Steven Steven.Mullins at dmme.virginia.gov
Tue Dec 4 12:01:28 EST 2007


Frank,

Works perfect!  Now I understand OGR's data handling better too.  

Many thanks,

Steve

-----Original Message-----
From: Frank Warmerdam [mailto:warmerdam at pobox.com]
Sent: Tue, December 04, 2007 11:26 AM
To: Mullins, Steven
Cc: gdal-dev at lists.osgeo.org
Subject: Re: FW: [gdal-dev] Shapefile read/write


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