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
If you don't mind using regular expressions, then this function would give you much power in renaming files:
import re, glob, os
def renamer(files, pattern, replacement):
for pathname in glob.glob(files):
basename= os.path.basename(pathname)
new_filename= re.sub(pattern, replacement, basename)
if new_filename != basename:
os.rename(
pathname,
os.path.join(os.path.dirname(pathname), new_filename))
So in your example, you could do (assuming it's the current directory where the files are):
renamer("*.doc", r"^(.*)\.doc$", r"new(\1).doc")
but you could also roll back to the initial filenames:
renamer("*.doc", r"^new\((.*)\)\.doc", r"\1.doc")
and more.