Is there an easy way to rename a group of files already contained in a directory, using Python?
Example: I have a directory full of *.doc files an
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).