Batch Renaming of Files in a Directory
I prefer writing small one liners for each replace I have to do instead of making a more generic and complex code. E.g.:
This replaces all underscores with hyphens in any non-hidden file in the current directory
import os
[os.rename(f, f.replace('_', '-')) for f in os.listdir('.') if not f.startswith('.')]
Such renaming is quite easy, for example with os and glob modules:
import glob, os
def rename(dir, pattern, titlePattern):
for pathAndFilename in glob.iglob(os.path.join(dir, pattern)):
title, ext = os.path.splitext(os.path.basename(pathAndFilename))
os.rename(pathAndFilename,
os.path.join(dir, titlePattern % title + ext))
You could then use it in your example like this:
rename(r'c:\temp\xx', r'*.doc', r'new(%s)')
The above example will convert all *.doc
files in c:\temp\xx
dir to new(%s).doc
, where %s
is the previous base name of the file (without extension).