I have a set of functions I am using to read shapefiles and produce some geojson files for parsing:
def read_shapefile(path, buffer = []):
# read the shapefile
reader = shapefile.Reader(path)
fields = reader.fields[1:]
field_names = [field[0] for field in fields]
#buffer = []
for sr in reader.shapeRecords():
for i in range(len(sr.record)):
if type(sr.record[i]) == bytes:
sr.record[i] = str(sr.record[i])
atr = dict(zip(field_names, sr.record))
geom = sr.shape.__geo_interface__
buffer.append(dict(type="Feature", \
geometry=geom, properties=atr))
return buffer
def write_geojson(buffer):
# write the GeoJSON file
#print(buffer)
print(type(buffer))
geojson = open("pyshp-demo.json", "w")
geojson.write(dumps({"type": "FeatureCollection",\
"features": buffer}, indent=2) + "\n")
geojson.close()
def read_shapes():
""" read all of the shapes in our shape directory and write them to geojson"""
files = get_file_list(SHAPE_DIRECTORY, [".shp"])
print(files)
buffer = []
for file in files:
buffer = read_shapefile(file, buffer)
write_geojson(buffer)
which works fine but sometimes I am getting files in X\Y instead of lat long. I see How to convert projected coordinates to lat/lon using Python? which is useful for converting single points but is there any way inside read_shapefile I could easily apply the conversion to the whole geometry object instead of parsing through my end result line by line?