Thursday, March 18, 2010

Batch rename folders using python and excel

A simple app that generates a csv file of folders and then lets you add the new names. This manipulation is usually best done in Excel. So I have decided it is a kind of best combination to batch rename files or folders


File for getting folder names

' Get root directory'
ROOT_DIR = "D:\\Pictures\\"
OUT_FILE = "dirNames.csv"

' Get list of directories'
folderNames = [dirs for dirs in os.listdir(ROOT_DIR) if os.path.isdir(ROOT_DIR+dirs)]

'print one by one and name it as outdir.csv'
f = open(ROOT_DIR+OUT_FILE,"w")
for fol in folderNames:
    f.write(fol+"\n")
f.close()

File to rename
ROOT_DIR = "D:\\Pictures\\"
RENAME_FILE = "newNames.csv"
os.chdir(ROOT_DIR)

f = open(ROOT_DIR+RENAME_FILE,"r")
names = f.readlines()
f.close()

for n in names:
    nmsList = n.strip().split(',')
    print nmsList[0]+" being renamed to : "+nmsList[1]
    os.rename(nmsList[0],nmsList[1])


As usual given with no guarantees. Use at your own risk

Bookmark and Share

No comments:

Post a Comment