Skip to content

Instantly share code, notes, and snippets.

@rclark
Last active December 10, 2015 20:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rclark/bd08f0e7476ab6939bab to your computer and use it in GitHub Desktop.
Save rclark/bd08f0e7476ab6939bab to your computer and use it in GitHub Desktop.
import ogr
# First, you'll need to have made a .vrt file that points at the .csv file
# and defines the lat / long fields and spatial reference.
# Here is an example:
#<OGRVRTDataSource>
# <OGRVRTLayer name="test">
# <SrcDataSource>test.csv</SrcDataSource>
# <GeometryType>wkbPoint</GeometryType>
# <LayerSRS>WGS84</LayerSRS>
# <GeometryField encoding="PointFromColumns" x="Longitude" y="Latitude"/>
# </OGRVRTLayer>
#</OGRVRTDataSource>
# Open the CSV file as a DataSource
csv_datasource = ogr.Open("filename.vrt")
# Get the Layer within the DataSource. There's only one layer in a CSV file so...
csv_layer = csv_datasource.GetLayer(0)
# Open a connection to a PostgreSQL database
pg_datasource = ogr.Open("PG:host=127.0.0.1 port=5432 user=writeuser password=secret dbname=datastore")
# Copy the CSV Layer into PostgreSQL. Second argument is the name of the table to be created.
pg_datasource.CopyLayer(csv_layer, "test")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment