# Batch renaming of shapefiles using ArcPy and folder name where shapefile is stored?

I am very new to Python and wondered if anyone had any idea how to do this?

I have ~100+ shapefiles named 'land boundary' within the folder of their site name.

Is this possible using Python in ArcGIS?

• If you just want to replace a few characters in the name, or change the name in a standardized way, have a look at this question. – Martin May 14 '14 at 10:35
• Welcome to GIS SE! If the Q&Q @Martin linked to does not do what you are looking for, then be sure to edit your Question to provide more details about precisely what you are wanting to do with ArcPy. – PolyGeo May 14 '14 at 11:13

Not sure exactly what you want. I've prepare two scripts, I supose you want one of this, maybe with a little variation.

Having this file structure:

C:\test\foo\bar.dbf
C:\test\foo\bar.sbn
C:\test\foo\bar.sbx
C:\test\foo\bar.shp
C:\test\foo\bar.shx


Script 1:

Renames the files in the same folder.

import os
import ntpath

# Replace with your folder
path = "C:/test"

for root, dir, files in os.walk(path):
for file in files:
dirname = ntpath.basename(root)
ori = root + '/' + file
dest =  root + '/' + dirname + file
os.rename(ori, dest)


Result:

C:\test\foo\foobar.dbf
C:\test\foo\foobar.sbn
C:\test\foo\foobar.sbx
C:\test\foo\foobar.shp
C:\test\foo\foobar.shx


Script 2:

Renames the files in the parent folder.

import os
import ntpath

# Replace with your folder
path = "C:/test"

for root, dir, files in os.walk(path):
for file in files:
parentdir = os.path.dirname (root)
dirname = ntpath.basename(root)
ori = root + '/' + file
dest =  parentdir + '/' + dirname + file
os.rename(ori, dest)


Result:

C:\test\foobar.dbf
C:\test\foobar.sbn
C:\test\foobar.sbx
C:\test\foobar.shp
C:\test\foobar.shx


NOTE: Both scripts renames every file under the specified path, not only shapefiles.

• Thank you very much: I'll let you know how I get on with this when I;ve worked out how to add this code as a script – Al Sherren May 14 '14 at 16:56
• How to add folder name at suffix. I tried out but it got added "Folder name" after file extension? – GIS Data Butcher Apr 27 '16 at 13:21
• Change line [dest = root + '/' + dirname + file] to [dest = root + '/' + (dirname + '.').join(file.split('.'))] – cag Apr 28 '16 at 5:24