Monday, 1 July 2019

arcpy - Multiple rename shapefiles and feature classes in python


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?



Answer



The following would do it with your directories:


import arcpy

InWork = ["D:\\GIS_Temp\Folder A", "D:\\GIS_Temp\\Folder"]

for ws in InWork:

arcpy.env.workspace = ws
datasets = arcpy.ListFeatureClasses()
for fc in datasets:
newName = fc.replace(' ','_')
arcpy.Rename_management(fc, newName[:-4])

Note the [:-4], which I do to strip the .shp from the original name. Otherwise Python would name it, for example, dataset.shp.shp and that would crash ArcPy.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...