[GIS] ogr2ogr/python overwrite PostGIS table

ogrogr2ogrpython

Using ogr2ogr command line I can overwrite or append to an existing PostGIS table like:

ogr2ogr -f "PostgreSQL"-overwrite PG:"host=myserver port=54321 user=user dbname=mydbname password=mypassword" C:/Temp/my.shp

Next, I would like to incorporate this logic into a python script. I've found some useful sites, however I'm not finding any examples using these methods.

Open Source RS/GIS Python Week 1

PostGIS OGR Examples

Append a shapefile to a postgis table using the GDAL/OGR Python interface

How do you overwrite or append to a PostGIS table using ogr2ogr commands in python?

Best Answer

Not a direct answer using python GDAL bindings but I have used the python subprocess module to call the GDAL command line utility to batch load Shapefiles into into postGIS. Something like this would work:

for shapefile in shp_list:
    program = "C:\Path\to\GDAL"
    command = 'ogr2ogr -f "PostgreSQL"-overwrite PG:"host=myserver port=54321 user=user dbname=mydbname password=mypassword" %s' shapefile
    input_command = [command]
    command_run = subprocess.call([program, input_command])
    if command_run == 0:
        print "Its worked!!"
    else:
        print "Table exists so appending"
        input_command = [command]
        command_run = subprocess.call([program, input_command])
        command = 'ogr2ogr -f "PostgreSQL"-overwrite PG:"host=myserver port=54321 user=user dbname=mydbname password=mypassword" C:/Temp/my.shp'
        command_run = subprocess.call([program, input_command])

If the ogr2ogr command fails (because the table already exists) then a second command is tried this time using the append option (-f).

Its not fool proof but does the job if you can be sure you wont be getting any other errors from the command line.

Related Question