Skip to content

Instantly share code, notes, and snippets.

@bryanluman
Last active August 29, 2015 13:57
Show Gist options
  • Save bryanluman/9370639 to your computer and use it in GitHub Desktop.
Save bryanluman/9370639 to your computer and use it in GitHub Desktop.
Fix shapefile indexes recursively thanks to NIM098173
import os
import sys
import arcpy
from datetime import datetime
def has_no_index(shp_filepath):
sbx = shp_filepath[0:-3] + 'sbx'
sbn = shp_filepath[0:-3] + 'sbn'
return not ( os.path.exists(sbx) and os.path.exists(sbn) )
def file_datetime(filepath):
mtime = os.stat(filepath).st_mtime
return datetime.fromtimestamp(mtime)
def index_outdated(shp_filepath):
sbx_dt = file_datetime(shp_filepath[0:-3] + 'sbx')
sbn_dt = file_datetime(shp_filepath[0:-3] + 'sbn')
shp_dt = file_datetime(shp_filepath)
return (shp_dt > sbx_dt) or (shp_dt > sbn_dt)
def fix_shapefile_indicies_for_dir(arg, dirname, names):
for filename in names:
if filename[-3:].lower() == 'shp':
filepath = os.path.join(dirname, filename)
if has_no_index(filepath) or index_outdated(filepath):
print 'Generating index for %s' % filepath
try:
arcpy.AddSpatialIndex_management(filepath)
except Exception as e:
print e.message
if __name__ == '__main__':
toppath = sys.argv[1]
os.path.walk(toppath, fix_shapefile_indicies_for_dir, None)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment