Python Shapefiles – Multiple Rename of Shapefiles and Feature Classes in Python

arcpyshapefile

I have multiple shapefiles, in different sources (D:\GIS\Folder A", "D:\GIS_Temp\Name". And some of them have space in their name (File X, File Y, etc).

What should be the code that could rename all shapefiles in those folders, and change space with underscore, so the name of shapefiles would be File_X, File_Y, and so on…


When I try with this code:

import os, sys, arcpy
InWork =  ["D:\\GIS_Temp\Folder A", "D:\\GIS_Temp\\Folder B", "D:\\GIS_Temp\\Folder C"]
arcpy.env.workspace = InWork
for thisFC in arcpy.ListFeatureClasses():
newName = thisFC.replace(" ","_")
arcpy.Rename_management(thisFC,newName)

I put the folders in InWork, and I still get an error.

Runtime error
Traceback (most recent call last):
File "", line 3, in
File "c:\program files\arcgis\desktop10.1\arcpy\arcpy\geoprocessing_base.py", line 515, in set_
self[env] = val
File "c:\program files\arcgis\desktop10.1\arcpy\arcpy\geoprocessing_base.py", line 567, in setitem
ret_ = setattr(self._gp, item, value)
RuntimeError: Object: Error in accessing environment

What am I doing wrong?

Best Answer

I would use Rename_management to make sure you get all the parts to the shape file:

import os, sys, arcpy

InWork = sys.argv[1] # this script designed to be used as a tool, replace with a path if you wish
arcpy.env.workspace = InWork

for thisFC in arcpy.ListFeatureClasses():
    newName = thisFC.replace(" ","_")
    arcpy.Rename_management(thisFC,newName)

Note the .replace() does the main work and can be called many times to change any characters (commas, dashes etc). Note for the purposes of your previous question you must also get rid of starting underscores and numbers, after the first character they're ok but you can't start with a number or underscore.

To make this faster you could consider only renaming if changed:

if thisFC != newName:
    arcpy.Rename_management(thisFC,newName)
Related Question