Archive
Posts Tagged ‘batch’
Rename multiple files
November 2, 2010
Leave a comment
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.