Home > python > Rename multiple files

Rename multiple files

Problem

I scanned in 66 pages that are numbered from 11 to 76. However, the scanning software saved the files under the names Scan10032.JPG, Scan10033.JPG, …, Scan10097.JPG. I want to rename them to reflect the real numbering of the pages, i.e. 11.jpg, 12.jpg, …, 76.jpg.

Solution

#!/usr/bin/env python

import glob
import re
import os

files = glob.glob('*.JPG')  # get *.JPG in a list (not sorted!)
files.sort()                # sort the list _in place_
cnt = 11                    # start new names with 11.jpg

for f in files:
    original = f                                    # save the original file name
    result = re.search(r'Scan(\d+)\.JPG', f)        # pattern to match
    if result:                                      # Is there a match?
        new_name = str(cnt) + '.jpg'                # create the new name
        print "%s => %s" % (original, new_name)     # verify if it's OK
        # os.rename(original, new_name)             # then uncomment to rename
        cnt += 1                                    # increment the counter

Comments are inside the source code.

If you need a simpler rename (like removing a part of the file names), you can also use the rename command. In this post I give an example for that.

About these ads
Categories: python Tags: , , , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

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.

Join 79 other followers

%d bloggers like this: