使用Python和Ogr将shp导入Postgis


14

我只是使用此技巧将Postgis表导出为shp, 但是无法使用相同的库(ogr)将shp导入Postgis。任何想法?非常感谢f。


1
您是否真的需要使用python来执行此操作,还是只是尝试导入文件?我跌倒了,您需要做的是导入文件,然后在命令行上使用ogr2​​ogrogr2ogr -f "PostgreSQL" PG:”dbname=DBNAME host=localhost" file.shp -nln TABLENAME
Jesse Crocker

Answers:


29

在纯Python中,无需使用子流程模块(例如,不赞成使用os.system)来调用ogr2ogrshp2pgsql

1)与OGR

2)OGR和psycopg2从书Python的地理空间发展(埃里克·Westra),第7章,第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)仅与psycopg2

4)与psycopg2和其他空间库

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.