swapextensions - A tiny Python script to swap file extensions throughout a directory tree.    
         
   

Get swapextensions.py 0.4 (posted 23 July 2002)

Save as "swapextensions.py" into a suitable folder, ideally your Python/Lib folder, created when you install Python.

IMPORTANT: You use swapextensions.py at your own risk. Use it with care.

swapextensions.py will do what you tell it to do. If you point it to your C-drive, it will happily swap the extension of every file in every subfolder on the drive that meets the criteria set in the script. If you do this, please do not send me moany e-mails complaining about the script. Instead, send me e-mails full of praise at how efficiently swapextensions.py trashed the names of all your most important files. If in doubt, test on a dummy set of files first.

Read the source, so you can see how it works and what it does. Note that the script looks for all files within a directory tree, i.e. not just the directory (folder) you point it at, but also that directory's sub-folders and their sub-folders and so on.

Mail me if you use the script and would like to comment on it.

   
         
    The script requires Python to be installed on your computer. Go to www.python.org to download Python.    
         
   

Using swapextensions.py
You need to send in three arguments: the directory where the script will do its work, and the "before" and "after" extension strings. The dot at the front of the extension is optional.

Example:

import swapextensions
swapextensions.swapextensions(r"C:\mysite","asp","htm")

Wish List

At some point I will:

  • add some validation so the directory can be checked to see it it exists

Version history

Version 0.4 is a new, improved, swapextensions.py
This script made it into the Python Cookbook book. The editors gave it a good going over, so I'm reposting it.

Changes:

  • The "checking for leading dots" is now in the swapextensions function, not in the call back. This now only gets done once, which is as it should be.
  • The script now explicitly only affects the end of the file name, so files that happen to have ."extension" *inside* their name as well as at the end will only get the real extension changed. This makes the script more targeted, and so more safe.
  • The redundant import of string survived the editing process. I've now removed it.

Version 0.3 is functionally identical to version 0.2, but it is shorter and neater.

Version 0.2  (posted 23 August 2000) is still available, if anyone is interested.

   
         
    <BACK TO PYTHON PAGE>           <HOME>