Shapefile into geojson conversion python 3
Please check out the following library: https://pypi.python.org/pypi/pyshp/1.1.7
import shapefilefrom json import dumps# read the shapefilereader = shapefile.Reader("my.shp")fields = reader.fields[1:]field_names = [field[0] for field in fields]buffer = []for sr in reader.shapeRecords(): atr = dict(zip(field_names, sr.record)) geom = sr.shape.__geo_interface__ buffer.append(dict(type="Feature", \ geometry=geom, properties=atr)) # write the GeoJSON file geojson = open("pyshp-demo.json", "w")geojson.write(dumps({"type": "FeatureCollection", "features": buffer}, indent=2) + "\n")geojson.close()
As noted in other answers, you could use geopandas:
import geopandasshp_file = geopandas.read_file('myshpfile.shp')shp_file.to_file('myshpfile.geojson', driver='GeoJSON')
To add onto @alexisdevarennes.
You can now convert to geojson using PyShp in 1 or two lines:
import shapefilewith shapefile.Reader("shapefile.shp") as shp: geojson_data = shp.__geo_interface__
or
geojson_data = shapefile.Reader("shapefile.shp").__geo_interface__
example usage:
>>> geojson_data["type"]'MultiPolygon'