16

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?

Taras
35.8k5 gold badges77 silver badges151 bronze badges
asked Mar 18, 2014 at 16:02
1
  • 1
    Do you really need to use python to do it, or are you just trying to import the file? I fall you need to do is import the file then use ogr2ogr on the command line ogr2ogr -f "PostgreSQL" PG:"dbname=DBNAME host=localhost" file.shp -nln TABLENAME Commented Mar 18, 2014 at 16:37

1 Answer 1

31

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

answered Mar 18, 2014 at 18:51
1
  • Option 3 does not actually have an answer to the question. Commented Aug 17, 2021 at 11:21

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.