#!/bin/env python """Change extensions of all matched files in a directory. Usage: change_extensions ext1 ext2 [dir1 [dir2 [...]]] Where "ext1" is the extension files currently have, "ext2" is the extension they should have, and "dir" is a list of directories in which to perform the renaming (defaulting to the current directory). An `extension' is the last section of a filename, starting with the final "." in the filename and continuing to its end - for instance, in "fred.jim.bob" the extension is ".bob". If "ext1" is the empty string (""), then files with no extension will be given extension "ext2" (note that this obviously won't rename files called something like "look.no.extension"!) If "ext2" is the empty string (""), then the files will end up with no extension. Note that if either of "ext1" or "ext2" is non-empty, and does not start with a ".", then a "." will be prepended. """ import sys import string import os #import posix #import posixpath def doit(dir,ext1,ext2): """Rename files in "dir" with extension "ext1" to extension "ext2".""" print "Directory",dir files = os.listdir(dir) files.sort() for file in files: root,ext = os.path.splitext(file) if ext == ext1: oldfile = os.path.join(dir,file) newfile = os.path.join(dir,'n-'+root+ext2) print "Renaming %s to %s"%(oldfile,newfile) if os.path.exists(os.path.join(dir,newfile)): print "*** Unable to rename %s to %s (already exists"%(oldfile, newfile) else: try: os.rename(oldfile,newfile) except: print "*** Unable to rename %s"%oldfile def main(): """Called from the toplevel.""" # Extract our arguments arg_list = sys.argv[1:] # What arguments do we have? if len(arg_list) < 2: print __doc__ return ext1 = arg_list[0] ext2 = arg_list[1] # Make sure the extensions start with "." # (unless they're the empty string) if len(ext1) != 0 and ext1[0] != ".": ext1 = "."+ext1 if len(ext2) != 0 and ext2[0] != ".": ext2 = "."+ext2 # Sort out which directories we want dirs = arg_list[2:] if len(dirs) == 0: dirs = ["."] # And process each of them for dir in dirs: # Let's be cautious... if os.path.isdir(dir): doit(dir,ext1,ext2) else: print "%s is not a directory"%dir # If we're run from the shell, run ourselves if __name__ == "__main__": main() # ---------------------------------------------------------------------- # [X]Emacs local variables declaration - place us into python mode # Local Variables: # mode:python # py-indent-offset:4 # End: