Thursday, April 2, 2015

Python (ArcPy) - Get rid of suffixes from multiple shapefiles in a folder


Let's say that I have several shapefiles in a folder and I would like to remove the suffixes from each shapefile and overwrite the previous files.

For Example:


Here is the Python (ArcPy) code..

import os, sys, arcpy

#InFolder = sys.argv[1] # make this a hard set path if you like

InFolder = "I:\\python\\GIS-data-Management\\Globalmapper" # make this a hard set path if you like

arcpy.env.workspace = InFolder
CapitalKeywordsToRemove = ["_AREAS","_LINES"]# MUST BE CAPITALS

DS_List = arcpy.ListFeatureClasses("*.shp","ALL") # Get a list of the feature classes (shapefiles)
for ThisDS in DS_List:
    NewName = ThisDS # set the new name to the old name

    # replace key words, searching is case sensitive but I'm trying not to change the case
    # of the name so the new name is put together from the original name with searching in
    # upper case, use as many key words as you like

    for CapKeyWord in CapitalKeywordsToRemove:
        if CapKeyWord in NewName.upper():
            # remove the instance of CapKeyWord without changing the case
            NewName = NewName[0:NewName.upper().find(CapKeyWord)] + NewName[NewName.upper().find(CapKeyWord) + len(CapKeyWord):]

    if NewName != ThisDS:
        if not arcpy.Exists(NewName):
            arcpy.AddMessage("Renaming " + ThisDS + " to " + NewName)
            arcpy.Rename_management(ThisDS , NewName)
        else:
            arcpy.AddWarning("Cannot rename, " + NewName + " already exists")
    else:
        arcpy.AddMessage("Retaining " + ThisDS)

No comments:

Post a Comment