-
Notifications
You must be signed in to change notification settings - Fork 0
/
shp_to_postgis.py
43 lines (40 loc) · 1.52 KB
/
shp_to_postgis.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#https://github.com/SereneWizard/shapefile-to-postgis/blob/master/Shapefile_to_postgis.ipynb
# Import necessary libraries
import os
import glob
import psycopg2
import fiona
from shapely.geometry import Polygon
infname = glob.glob('vector/*.shp')[0]
with fiona.drivers():
with fiona.open(infname) as src:
geom = src.crs
feat = src.next()
attributes = feat['properties'].keys()
gemtype = feat['geometry']['type']
connection = psycopg2.connect(database="mydatabase",
user="myusername",
password="mypassword",
host="localhost")
cursor = connection.cursor()
tablename = "Mclean_Dupage"
cursor.execute("DROP TABLE IF EXISTS {}".format(tablename))
cursor.execute("""
CREATE TABLE {}
(id SERIAL PRIMARY KEY,
COUNTY_NAM VARCHAR NOT NULL,
CO_FIPS BIGINT NOT NULL,
geom GEOMETRY)""".format(tablename))
connection.commit()
with fiona.drivers():
with fiona.open(infname) as src:
for i in src:
record = list(i['properties'].values())
print ("{} county has {} fips".format(*record))
geometry = Polygon(i['geometry']['coordinates'][0])
wktgeometry = geometry.wkt
cursor.execute("""
INSERT INTO {} (COUNTY_NAM, CO_FIPS, geom)
VALUES ('{}', {}, ST_GeomFromText('{}'))
""".format(tablename, *record, wktgeometry))
connection.commit()