Recipe 2.17. Swapping One File Extension for Another Throughout a Directory TreeCredit: Julius Welby ProblemYou need to rename files throughout a subtree of directories, specifically changing the names of all files with a given extension so that they have a different extension instead. SolutionOperating on all files of a whole subtree of directories is easy enough with the os.walk function from Python's standard library: import os def swapextensions(dir, before, after): if before[:1] != '.': before = '.'+before thelen = -len(before) if after[:1] != '.': after = '.'+after for path, subdirs, files in os.walk(dir): for oldfile in files: if oldfile[thelen:] == before: oldfile = os.path.join(path, oldfile) newfile = oldfile[:thelen] + after os.rename(oldfile, newfile) if _ _name_ _=='_ _main_ _': import sys if len(sys.argv) != 4: print "Usage: swapext rootdir before after" sys.exit(100) swapextensions(sys.argv[1], sys.argv[2], sys.argv[3]) DiscussionThis recipe shows how to change the file extensions of all files in a specified directory, all of its subdirectories, all of their subdirectories, and so on. This technique is useful for changing the extensions of a whole batch of files in a folder structure, such as a web site. You can also use it to correct errors made when saving a batch of files programmatically. The recipe is usable either as a module to be imported from any other, or as a script to run from the command line, and it is carefully coded to be platform-independent. You can pass in the extensions either with or without the leading dot (.), since the code in this recipe inserts that dot, if necessary. (As a consequence of this convenience, however, this recipe is unable to deal with files completely lacking any extension, including the dot; this limitation may be bothersome on Unix systems.) The implementation of this recipe uses techniques that purists might consider too low levelspecifically by dealing mostly with filenames and extensions by direct string manipulation, rather than by the functions in module os.path. It's not a big deal: using os.path is fine, but using Python's powerful string facilities to deal with filenames is fine, too. See AlsoThe author's web page at http://www.outwardlynormal.com/python/swapextensions.htm. |