I've got a similar question to this one How to programmatically populate a shapefile field with polygon areas in OGR?, but the solution doesn't seem to be working for me. I am trying to import a shapefile from PostGIS into python using OGR, add a field, then populate the field with data from a csv based on an ID and the date. When I print the fields for the feature during the loop, the field gets the correct data but it isn't writing to the layer o3_proj (last two print statements). Am I using the SetFeature function incorrectly? I'm new to PostGIS and ogr, so please speak slowly!

import os, ogr, gdal, csv
driver = ogr.GetDriverByName('PostgreSQL')
datasource = driver.Open("PG: host='localhost' port='54321' dbname='chicago' user='postgres'", update = 1)

o3_proj = datasource.GetLayerByName('o3_monitors(geom3528)')

date = []
maxozone = []
aqi = []
aqs_site_id = []

f = csv.reader(open('/ozone/ozone_data.csv','rU'))
x = list(f)

for iii in range(1,len(x)):

daily_field = ogr.FieldDefn('temp_o3',ogr.OFTReal)

for feat in o3_proj:
    for jjj in range(0,len(date)):
        if aqs_site_id[jjj] == feat.GetField(0) and date[jjj] == '03/06/2005':
            print str(feat.GetField(0))+','+str(feat.GetField(1))+','+str(feat.GetField(2))+','+str(feat.GetField(3))+','+str(feat.GetField(4))+','+str(feat.GetField(5))+','+str(feat.GetField(6))
            print o3_proj.GetFeature(feat.GetFID()).GetField(6)

Result of the print statements:

  • Maybe you can simplify your code and variables names a little bit. Just enough to reproduce to problem once. But I think you are missing the CreateFeature statement. After you set a new field, you have to create the feature. Have a look at this example: pcjericks.github.io/py-gdalogr-cookbook/… – ustroetz Apr 6 '14 at 9:43

I suggest adding to the end of your script:-

o3_proj = None

As from other OGR tutorials I've read when working on my scripts, these calls at the end are suggested as necessary to ensure not just memory release, but also writing out data.

Let us know how it goes - as your use of SetFeature() does appear correct as far as I can tell. And I can see you've opened the file in update mode.

The other possibility I can think of, if my suggestion doesn't work - perhaps updating isn't supported for PostGIS files by the GDAL OGR driver?? You'd need to check.

| improve this answer | |

I know this isn't a straight answer to your question but I advice you to use pyshp to create and manipulate shape files. It is written in pure python and very easy to use. To edit a shapefile simply do:

e = shapefile.Editor(shapefile="shapefiles/test/name.shp")

Then add a field


Well, then kick off your loop and populate it by


When you are done, call the save method w.save(). That's it.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.