Skip to content

Instantly share code, notes, and snippets.

@emlys
Created June 16, 2022 23:33
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 emlys/60db94cb4017a78219a1aa1dadc0914d to your computer and use it in GitHub Desktop.
Save emlys/60db94cb4017a78219a1aa1dadc0914d to your computer and use it in GitHub Desktop.
convert a CSV of point coordinates to a geopackage
import os
from osgeo import gdal, ogr, osr
# Goal: Convert a CSV of point coordinates to a geopackage
# Create a test CSV
with open('test.csv', 'w') as csv:
csv.write('latitude,longitude\n')
csv.write('61,-150')
# Open the CSV as an ogr.DataSource
# Based on https://gis.stackexchange.com/questions/333510/accessing-ogr-driver-options-using-ogr-gdal-in-python
# I tried to set the options on the driver metadata
csv_driver = ogr.GetDriverByName('CSV')
csv_driver.SetMetadataItem('X_POSSIBLE_NAMES', 'longitude')
csv_driver.SetMetadataItem('Y_POSSIBLE_NAMES', 'latitude')
datasource = csv_driver.Open('test.csv')
# But the feature geometry is None indicating that
# the spatial columns were not recognized
layer = datasource.GetLayer()
feature = layer.GetNextFeature()
geom = feature.GetGeometryRef()
print(geom)
# Then I tried to set the options in an env variable
# like suggested here https://gis.stackexchange.com/a/335548
# I guess there is no corresponding env variable for the CSV driver.
os.environ["OGR_CSV_OPTIONS"] = "X_POSSIBLE_NAMES=longitude,Y_POSSIBLE_NAMES=latitude"
csv_driver = ogr.GetDriverByName('CSV')
datasource = csv_driver.Open('test.csv')
# still None
layer = datasource.GetLayer()
feature = layer.GetNextFeature()
geom = feature.GetGeometryRef()
print(geom)
# Then I tried opening the CSV with gdal.OpenEx because
# you can pass in open options. This returns a gdal.Dataset
dataset = gdal.OpenEx(
'test.csv',
open_options=[
'X_POSSIBLE_NAMES=longitude',
'Y_POSSIBLE_NAMES=latitude'])
# That worked, the feature has a geometry
layer = dataset.GetLayer()
feature = layer.GetNextFeature()
geom = feature.GetGeometryRef()
print(geom)
# Now I want to save it as a geopackage
# First I tried to use the OGR geopackage driver
gpkg_driver = ogr.GetDriverByName('GPKG')
# But this raises a TypeError because I am passing in a
# gdal.Dataset where it expects an ogr.DataSource
gpkg_driver.CopyDataSource(dataset, 'out.gpkg')
# Then I tried with the GDAL geopackage driver, but it raises
# ERROR 6: Only 1 (Grey/ColorTable), 2 (Grey+Alpha), 3 (RGB) or 4 (RGBA) band dataset supported
# I guess because CreateCopy assumes the dataset is raster?
gpkg_driver = gdal.GetDriverByName('GPKG')
gpkg_driver.CreateCopy('out.gpkg', dataset)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment