3

I have about 50 shapefiles I would like to change each of their file names which contains "2014" to "2015". I would like to use a python script but have not been able to figure out how to do it. I have tried using the sample script from Esri but to no avail. I've tried to use other examples I've found Looping through list of shapefiles to rename them using ArcPy? but unable to work it into my problem.

import os  
import arcpy  
arcpy.env.workspace =   
fcs = arcpy.ListFeatureClasses(fc)  
if fc.contains("4"):  
  arcpy.Rename_management("5")  
1
  • What error do you get when you run your code snippet?
    – PolyGeo
    Commented Jun 22, 2016 at 20:56

2 Answers 2

5

You could also avoid arcpy all together:

import os

os.chdir(r'C:\Set_to_your_directory')
substring = '2014'

files = os.listdir(os.curdir)
for file in files:
    if substring in file:
        file_new = file.replace("2014","2015")
        os.rename(file, file_new)

This will replace "2014" with "2015" for any file in a folder. It is also possible to place filters for the relevant shapefile extensions.

1
  • Thanks for the help, I used this to update a folder with .MXDs
    – whyzar
    Commented Jun 23, 2016 at 14:00
4

You can search for a substring in a string using if (substring) in (string), and then use string.replace() to replace the value you find.

import arcpy, os  
arcpy.env.workspace = r"d:\Temp\SE\RenShapes"
fcs = arcpy.ListFeatureClasses("*.shp") 
for fc in fcs: 
    if "2014" in fc:
        x = fc.replace("2014", "2015")
        arcpy.Rename_management(fc, x)

This will replace 2014 with 2015 in any shapefile name that contains it.

0

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.