Wednesday 24 February 2016

Import shp to Postgis using Python and ogr



I just export a Postgis Table to shp using this tips but I'm not able to import a shp to Postgis using the same library(ogr). Any idea? Thanks a lot f.



Answer



In pure Python, without using the subprocess module (os.system is deprecated) to call ogr2ogr or shp2pgsql, for example):


1) with ogr



2) with ogr and psycopg2 from the book Python Geospatial Development (Eric Westra), Chapter 7, p.219


import os.path  
import psycopg2
import osgeo.ogr
connection = psycopg2.connect("dbname=... user=...")

cursor = connection.cursor()
cursor.execute("DELETE FROM countries")
srcFile = os.path.join("DISTAL-data", "TM_WORLD_BORDERS-0.3","TM_WORLD_BORDERS-0.3.shp")
shapefile = osgeo.ogr.Open(srcFile)
layer = shapefile.GetLayer(0)
for i in range(layer.GetFeatureCount()):
feature = layer.GetFeature(i)
name = feature.GetField("NAME").decode("Latin-1")
wkt = feature.GetGeometryRef().ExportToWkt()
cursor.execute("INSERT INTO countries (name,outline) " +"VALUES (%s, ST_GeometryFromText(%s, " +"4326))", (name.encode("utf8"), wkt))


connection.commit()

3) with psycopg2 only



4) with psycopg2 and other spatial libraries



No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...