[GIS] Renaming shapefiles using loop in Python

arcpyshapefile

I'm trying to clean up a list of shapefiles that I've created using GME. I have a series of shapefiles (polylines and polygons) that are named "ID_final_kde.img_LSCV.shp" and "ID_final_kde.img_LSCV_poly.shp", where ID is unique to each individual. I'm trying to rename the polylines to "ID_final_LSCV.shp" and the polygons to "ID_final_LSCV_poly.shp", to no avail.

Here's what I've been trying:

# import modules
import arcpy, os, arcinfo, xlwt,time, glob
from arcpy.sa import *

arcpy.CheckOutExtension('spatial')

path = os.getcwd()
arcpy.env.workspace = path + '\\fawn_locations\\FINAL'
arcpy.env.overwriteOutput = True

lines=arcpy.ListFeatureClasses(feature_type='Polyline')
for each in lines:
    arcpy.Rename_management(each, each[:-16] + 'LSCV')

poly=arcpy.ListFeatureClasses(feature_type='Polygon')
for each in poly:
    arcpy.Rename_management(each, each[:-20] + 'LSCV_poly')

This code renames the .shp file, but not the associated .cfg, .prj, or .shx files, so I can no longer open the shapefile in ArcMap. How can I loop through the folder, renaming all the files while preserving their extensions?

I'm just learning python.

Best Answer

I don't believe you even need arcpy for this necessarily. I think you just need to change the name of all the shapefiles with that name. So to rename from 'abc' to 'def' you would have abc.shp, abc.cfg, abc.prj, etc. become def.shp, def.cfg, def.prj, etc.

import sys
import os

def renameFiles(path):
    for root, dirs, files in os.walk(path):
        for file in files:
            filename, extension = os.path.splitext(file)
            os.rename(os.path.join(path, file), os.path.join(path, filename[:-20] + 'LSCV_poly' + extension))

renameFiles(pathToRename)
Related Question