Change the extension of multiple files in a chosen directory and it’s sub-directories with Python

To change the extension of a single or multiple files, we just have to use the os module and some of it’s usefull methods.
The following function changes the extention of all the files in the directory that you specify (and in it’s sub-directories if you want):

import os

def change_file_ext(cur_dir, old_ext, new_ext, sub_dirs=False):
    if sub_dirs:
        for root, dirs, files in os.walk(cur_dir):
            for filename in files:
                file_ext = os.path.splitext(filename)[1]
                if old_ext == file_ext:
                    oldname = os.path.join(root, filename)
                    newname = oldname.replace(old_ext, new_ext)
                    os.rename(oldname, newname)
    else:
        files = os.listdir(cur_dir)
        for filename in files:
            file_ext = os.path.splitext(filename)[1]
            if old_ext == file_ext:
                newfile = filename.replace(old_ext, new_ext)
                os.rename(filename, newfile)

The first argument, cur_dir, is the directory that your files are in. The second one, old_ext, is the extension that you want to change. The third argument, new_ext, is the new extension that your files want to have, and the last argument, sub_dirs, is if you want to apply the changes also into the sub-directories of your chosen directory. By default it’s flag is set to False (thus it is optional), so no changes will take place into the sub-dirs. You can change of course it’s default behaviour to True if you want, but I prefer it more this way, because if I ever forget myself and all I want to do is change a file only in the current directory, with it’s default flag set to True it will also apply the changes into the sub-dirs, and that’s something I may not want to happen.
Let’s look at two examples of it’s use:

# change all .txt files to .html only in this directory
change_file_ext('/home/user/my_files', '.txt', '.html')

# change all .txt files to .html also in sub-directories
change_file_ext('/home/user/my_files', '.txt', '.html', True)

Now, if we want to change muttiple files with different extensions into a single extension all at once, ie change some ‘.txt’, ‘.htm’, ‘.info’ files to ‘.html’, then we can use the following slight modification of our function:

import os

def change_multi_file_ext(cur_dir, extensions, new_ext, sub_dirs=False):
    if sub_dirs:
        for root, dirs, files in os.walk(cur_dir):
            for filename in files:
                file_ext = os.path.splitext(filename)[1]
                for ext in extensions:
                    if ext == file_ext:
                        oldname = os.path.join(root, filename)
                        newname = oldname.replace(ext, new_ext)
                        os.rename(oldname, newname)
    else:
        files = os.listdir(cur_dir)
        for filename in files:
            file_ext = os.path.splitext(filename)[1]
            for ext in extensions:
                if ext == file_ext:
                    newfile = filename.replace(ext, new_ext)
                    os.rename(filename, newfile)

Here all the arguments are the same except the second one. The second argument is a tuple (or a list) that holds our extensions that we want to change and thus we must define it somewhere in our code before we call the function.
For example:

# define our extensions that we want to change
extensions = ('.txt', '.htm', '.info')
# change all .txt, .htm, .info files to .html
# only in this directory
change_multi_file_ext('/home/user/my_files', extensions, '.html')

# change all .txt, .htm, .info files to .html
# also in sub-directories
change_multi_file_ext('/home/user/my_files', extensions, '.html', True)

Pretty simple usage of both functions and easy to implement them in your code.

IMPORTANT NOTE: You can change a file’s extension to none if you want, ie change ‘my_file.txt’ just to ‘my_file’ (remove the extension), but not the opposite, at least with the methods I provided. If you try that, then I must warn you that you may lose a lot of files and sub-dirs in your selected dir, so never never never even think of trying it. Be warned.
You can do this if you want:

# remove the extension from the .txt files
change_file_ext('/home/user/my_files', '.txt', '')

BUT NEVER NEVER NEVER DO THAT:

# most probably you will lose
# both files and sub-dirs with this
change_file_ext('/home/user/my_files', '', '.html')

The methods I presented here apply only to files THAT HAVE an extension, don’t you ever forget it.

Hope you found this post usefull.
Cheers!

About these ads

3 comments so far

  1. Stavvy on

    So what if we are trying to add a file extension to files that have no extension to begin with? How do you do that?

    • Stavvy on

      I figured out how to do with the command prompt so nevermind.

  2. Srinivas on

    I prefer to use windows native rename command to rename a file. If you need to rename files in bulk, like removing the existing extension, or changing extension, you can use small script shared here : http://www.windows-commandline.com/rename-file-extensions-bulk/


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: