Batch renaming of files

Suppose you have a directory of data files identified by filenames containing a date in the form data-DD-Mon-YY.txt where DD is the two-digit day number, Mon is the three-letter month abbreviation and YY is the last two digits of the year, for example '02-Feb-10'. The following program converts the filenames into the form data-YYYY-MM-DD.txt so that an alphanumeric ordering of the filenames puts them in chronological order.

import os
import sys

months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun',
          'jul', 'aug', 'sep', 'oct', 'nov', 'dec']

dir_name = sys.argv[1]
for filename in os.listdir(dir_name):
    # filename is expected to be in the form 'data-DD-MMM-YY.txt'
    d, month, y = int(filename[5:7]), filename[8:11], int(filename[12:14])
    m = months.index(month.lower())+1

    newname = 'data-20{:02d}-{:02d}-{:02d}.txt'.format(y, m, d)
    newpath = os.path.join(dir_name, newname)
    oldpath = os.path.join(dir_name, filename)
    print(oldpath, '->', newpath)
    os.rename(oldpath, newpath)

We get the month number from the index of corresponding abbreviated month name in the list months, adding 1 because Python list indexes start at 0.

For example, given a directory testdir containing the following files:


the command python testdir produces the output

testdir/data-02-Feb-10.txt -> testdir/data-2010-02-02.txt
testdir/data-10-Oct-14.txt -> testdir/data-2014-10-10.txt
testdir/data-22-Jun-04.txt -> testdir/data-2004-06-22.txt
testdir/data-31-Dec-06.txt -> testdir/data-2006-12-31.txt

See also Problem 4.4.4 and the datetime module (Section 4.5.3 of the book).