Skip to content

Instantly share code, notes, and snippets.

@agalea91
Forked from frankrowe/shp2gj.py
Last active September 29, 2017 08:06
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save agalea91/c0e0d1897d1d98a0029ac0baa02b9fca to your computer and use it in GitHub Desktop.
Save agalea91/c0e0d1897d1d98a0029ac0baa02b9fca to your computer and use it in GitHub Desktop.
PyShp, shp to geojson in python
# -*- coding: utf-8 -*-
from json import dumps
import shapefile
import click
@click.command()
@click.option(
'--f',
help="Filename",
default='my.shp'
)
def main(f):
# read the shapefile
reader = shapefile.Reader(f)
fields = reader.fields[1:]
field_names = [field[0] for field in fields]
buffer = []
for sr in reader.shapeRecords():
record = sr.record
# Make sure everything is utf-8 compatable
record = [r.decode('utf-8', 'ignore') if isinstance(r, bytes)
else r for r in record]
atr = dict(zip(field_names, record))
geom = sr.shape.__geo_interface__
buffer.append(dict(type="Feature", geometry=geom, properties=atr))
# write the GeoJSON file
with open('_'.join(f.split('.')[:-1]) + ".geo.json", "w") as geojson:
geojson.write(dumps({"type": "FeatureCollection",\
"features": buffer}, indent=2) + "\n")
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment