Renaming 2 thousand Files? Do it the Python way…

I ran into a situation earlier that I needed to bulk rename the file extension on a couple thousand files….

The first hurtle was that a majority of the files had a “\”  (or was it “/”?) in it.  Since I am on a Unix platform, it appears that the os.listdir function wasn’t able to see those files, since I believe that’s a reserved character.  These files were originally  created on an OS/2 based computer…

So I ended up using NameChanger, and it is a utility that works well…  Especially since it’s free..  The major drawback that I saw with NameChanger is that it didn’t seem to refresh it’s list of files once they were renamed…  And it clears the Find / Replace (Original Text / New Text) fields after running.

But once that hurdle was cleared, I needed to add file extensions…  So, what does any programmer do in a case like this? Write an python application:

import os
import sys
filenames = os.listdir (".")
for filename in filenames:
    if filename.endswith ("html.txt"):
        new_filename = filename.replace (".txt", "")
        os.rename (filename, new_filename)
    (shortname, extension) = os.path.splitext (filename)
    if extension == "":
        new_filename = filename +".txt"
        os.rename (filename, new_filename)

Yes, this is a very single purpose application, but if someone finds it useful feel free to use this as a starting point.

The application will gather a list of files that are in the current directory, anything that has an “.html.txt” extension will be renamed to .txt.  If there is no file extension then an .txt extension will be added…

Why did I make this?  I have a directory that I use to gather usenet messages in, and quicklook wouldn’t work until I renamed them to .txt (or .jpg, etc).  Since this directory was 99% text files, I needed a fast and dirty way to rename them, thus the script above.

Feel free to make any suggestions or to propose better methods just leave them in the comments…