Skip to content

Instantly share code, notes, and snippets.

@frankrowe
Last active November 1, 2022 17:54
Show Gist options
  • Save frankrowe/6071443 to your computer and use it in GitHub Desktop.
Save frankrowe/6071443 to your computer and use it in GitHub Desktop.
PyShp, shp to geojson in python
import shapefile
# read the shapefile
reader = 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
from json import dumps
geojson = open("pyshp-demo.json", "w")
geojson.write(dumps({"type": "FeatureCollection",\
"features": buffer}, indent=2) + "\n")
geojson.close()
Copy link

ghost commented Sep 6, 2017

Thanks for that nice little feature!

But I keep getting a decode error when running this script on the natural earth countries shapefile:

'utf8' codec can't decode byte 0xc5 in position 0: invalid continuation byte

But with the places shapefile it works perfectly fine!
Do you have any idea where that might come from?

@abdul-hamid-achik
Copy link

Thanks for that nice little feature!

But I keep getting a decode error when running this script on the natural earth countries shapefile:

'utf8' codec can't decode byte 0xc5 in position 0: invalid continuation byte

But with the places shapefile it works perfectly fine!
Do you have any idea where that might come from?

hey man i had the same issue but look

screen shot 2019-03-05 at 3 02 37 pm

basically before doing something like reader.shapeRecords() you gotta change the encoding type, in my case i was using some data from Guadalajara, MX and i had to change the encoding to be latin1 as you can see in the screenshot, then, it worked normally

@Curtisfrancis
Copy link

Curtisfrancis commented Apr 5, 2021

Thanks for that nice little feature!
But I keep getting a decode error when running this script on the natural earth countries shapefile:
'utf8' codec can't decode byte 0xc5 in position 0: invalid continuation byte
But with the places shapefile it works perfectly fine!
Do you have any idea where that might come from?

hey man i had the same issue but look

screen shot 2019-03-05 at 3 02 37 pm

basically before doing something like reader.shapeRecords() you gotta change the encoding type, in my case i was using some data from Guadalajara, MX and i had to change the encoding to be latin1 as you can see in the screenshot, then, it worked normally

Hey I am trying to do same thing using pycharm but its giving error feedback. can you assist me sire.

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