Skip to content

Instantly share code, notes, and snippets.

@alvincyh
Last active November 20, 2016 10:28
Show Gist options
  • Save alvincyh/f388242eeecc7c0e5e00331e03e3c237 to your computer and use it in GitHub Desktop.
Save alvincyh/f388242eeecc7c0e5e00331e03e3c237 to your computer and use it in GitHub Desktop.
Repair corrupted .shx file
# Based on the solution described here: http://geospatialpython.com/2011/11/generating-shapefile-shx-files.html
# Requires pyshp (pip install pyshp)
# Run script from shapefile folder
# Build a new shx index file
import fnmatch
import os
import shapefile
# List all the shapefiles
def find(pattern, path):
result = []
for root, dirs, files in os.walk(path):
for name in files:
if fnmatch.fnmatch(name, pattern):
result.append(os.path.join(root, name))
return result
shp_files = find('*.shp', '.')
for shp_file in shp_files:
# Explicitly name the shp and dbf file objects
# so pyshp ignores the missing/corrupt shx
shp = open(shp_file, "rb")
dbf = open(shp_file.replace("shp", "dbf"), "rb")
r = shapefile.Reader(shp=shp, shx=None, dbf=dbf)
w = shapefile.Writer(r.shapeType)
# Copy everything from reader object to writer object
w._shapes = r.shapes()
w.records = r.records()
w.fields = list(r.fields)
# saving will generate the shx
fixed_shp_file = os.path.join(os.path.dirname(shp_file),
"fixed_" + os.path.basename(shp_file))
w.save(fixed_shp_file)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment