Skip to content

Instantly share code, notes, and snippets.

@dkapitan
Last active March 2, 2021 05:20
Show Gist options
  • Save dkapitan/0ea7f170d5e961423dd3 to your computer and use it in GitHub Desktop.
Save dkapitan/0ea7f170d5e961423dd3 to your computer and use it in GitHub Desktop.
Working with shapefiles in Python and SQL Server
"""
SQL Server supports Geometry datatypes for GIS analytics. GIS data is often stored in ESRI .shp format
The GDAL/ogr library provides ample tools to work with shapefiles, and export them in wkt for importing in SQL Server
See:
http://gdal.org/python/
http://en.wikipedia.org/wiki/Well-known_text
http://en.wikibooks.org/wiki/Geospatial_Data_in_SQL_Server#Import_Functions
"""
from osgeo import ogr
path = '/Users/daniel/ownCloud/referentie_extern/GIS/Bridgis'
input = ogr.Open(path)
layer = input.GetLayer()
layer.ResetReading()
layerDefinition = layer.GetLayerDefn()
# get field names
fields = [layerDefinition.GetFieldDefn(i).GetName()
for i in range(layerDefinition.GetFieldCount())]
''' example how to get feature characteristics
print("Name - Type Width Precision")
for i in range(layerDefinition.GetFieldCount()):
fieldName = layerDefinition.GetFieldDefn(i).GetName()
fieldTypeCode = layerDefinition.GetFieldDefn(i).GetType()
fieldType = layerDefinition.GetFieldDefn(i).GetFieldTypeName(fieldTypeCode)
fieldWidth = layerDefinition.GetFieldDefn(i).GetWidth()
GetPrecision = layerDefinition.GetFieldDefn(i).GetPrecision()
print(fieldName + " - " + fieldType+ " " + str(fieldWidth) + " " + str(GetPrecision))
'''
outfile = open(path + "/ref_gis_pc4.csv", "w")
# write .csv header + last column 'geometry that contains wkt
outfile.write(';'.join(fields) + ';geometry\n')
for feature in layer:
row = [feature.GetField(field) for field in fields]
geom = feature.GetGeometryRef()
geom_name = geom.GetGeometryName()
wkt = geom.ExportToWkt()
row.append(wkt)
outfile.write(';'.join(row) + '\n')
@RazVais
Copy link

RazVais commented May 11, 2020

hi,
i'm trying to run your script.
all good up to the last row, when i try to join the row to the file, i get this error

TypeError: sequence item 0: expected str instance, int found
any ideas what am i doing wrong?

thnx,
raz

@dkapitan
Copy link
Author

dkapitan commented May 11, 2020 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment