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 and I want to rename them in a consistent way.
X.doc -> "new(X).doc"
Y.doc -> "new(Y).doc"
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
%s is the previous base name of the file (without extension).
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('.')]