3

I am trying to upgrade a simple script to list all shapefiles in a folder and if necessary in any folders within and then loop through the list of shapefiles and rename them.

import arcpy

# Set work environment
arcpy.env.workspace = "C:\\Users\\Rachael\\Documents\\Export"

# List shapefiles in folders
shp = arcpy.ListDatasets()

try:
  for shp in arcpy.ListDatasets():
    if arcpy.Exists("Histori2.shp"):
      arcpy.Rename_management("Histori2.shp", "H_BEV_CANS.shp")
2
  • 1
    Is there a reason you want to do this in arcpy? There are any number of Windows utilities for mass file renaming that would be a much simpler solution.
    – Llaves
    Commented Aug 10, 2013 at 4:05
  • Is there a formula or standard for renaming the files, or is it just hard coded with no particular method to it?
    – recurvata
    Commented Sep 24, 2014 at 14:29

2 Answers 2

6

You need to use arcpy.ListFeatureClasses(), not ListDatasets().

This code is directly from the online help. Just replace "CopyFeatures" with "Rename".

import arcpy
from arcpy import env
import os

# Set the workspace for the ListFeatureClass function
#
env.workspace = "c:/base"

# Use the ListFeatureClasses function to return a list of 
#  all shapefiles.
#
fcList = arcpy.ListFeatureClasses()

# Copy shapefiles to a file geodatabase
#
for fc in fcList:
    arcpy.CopyFeatures_management(fc, "d:/base/output.gdb" + os.sep + fc.rstrip(".shp"))
2

Well, you are defining shp and then using the same variable name in your loop for something else--this is bad practice, as it's confusing and you open your code up to unexpected results.

As it currently stands, you are only renaming one shapefile. Is there more hardcoded values after this?

It you know the names of the shapefiles and what you want to change them into, an easy way would be to dump these in a txt file, like this:

Histori2.shp,H_BEV_CANS.shp

Histori3.shp,H_CANS.shp

arcpy.env.workspace = r"C:\Users\Rachael\Documents\Export"
rename = [x.strip().split(",") for x in open(r"<path to text file>", "r")]

for old,new in rename:
  if arcpy.Exists(old):
    arcpy.Rename_management(old, new)
2
  • #Paul: I am try to upgrade the simple script you helped me with yesterday. There are more hardcoded values after this, I just clipped the first part of my script as I was trying to figure out how to loop through the dataset. And btw i did do research, I'm trying to learn it in steps so can grasp what I'm doing as i'm doing it. Baby steps...
    – Rachael
    Commented Aug 9, 2013 at 16:51
  • @Rachael Well if it's hardcoded, then I would actually bypass ListFeatuerClasses() entirely, and just use a txt file containing all of that.
    – Paul
    Commented Aug 9, 2013 at 16:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.