Skip to content

Instantly share code, notes, and snippets.

@sgillies
Last active November 8, 2019 10:23
Show Gist options
  • Save sgillies/5937555 to your computer and use it in GitHub Desktop.
Save sgillies/5937555 to your computer and use it in GitHub Desktop.
# 15 statement in this Fiona script, 12 after I move the prop_type function to Fiona.
# Compare to 31 statements for the ogr.py script at
# http://pcjericks.github.io/py-gdalogr-cookbook/layers.html#create-a-new-shapefile-and-add-data.
# The difference is that Fiona's schema and feature definition are declarative (using dict
# literals and comprehensions, not imperative (CreateField, SetField, etc) and that Fiona
# is designed to allow concise code.
from csv import DictReader
import fiona
from fiona.crs import from_epsg
# Open a collection for writing.
with fiona.open(
'volcanoes.shp', 'w',
crs=from_epsg(4326),
driver='ESRI Shapefile',
schema={
'geometry': 'Point',
'properties': {
'Name': 'str:24',
'Region': 'str:24',
'Latitude': 'float',
'Longitude': 'float',
'Elevation': 'float' }}
) as output:
# Make a mapping of property names to their Python types. This is used to
# convert text values from the input to proper Python values.
ptypes = {k: fiona.prop_type(v) for k, v in output.schema['properties'].items()}
def feature(row):
"""Converts a table row and its index to a Fiona feature dict."""
geom = {
'type': 'Point',
'coordinates': [float(row['Longitude']), float(row['Latitude'])] }
props = {k: ptypes[k](v) for k, v in row.items()}
return {
'type': 'Feature',
'geometry': geom,
'properties': props }
# Read rows and write all feature records in one go, using the feature()
# function defined above.
reader = DictReader(open("volcano_data.txt"), delimiter='\t')
output.writerecords(map(feature, reader))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment