The modified program is presented below.
import os
import sys
months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun',
'jul', 'aug', 'sep', 'oct', 'nov', 'dec']
try:
dir_name = sys.argv[1]
except IndexError:
print('No directory name provided. Usage:')
print('{} <dir_name>'.format(sys.argv[0]))
sys.exit(1)
if not os.path.exists(dir_name):
print('Directory {} does not exist'.format(dir_name))
sys.exit(1)
for filename in os.listdir(dir_name):
# filename is expected to be in the form 'data-DD-MMM-YY.txt'
try:
d, month, y = int(filename[5:7]), filename[8:11], int(filename[12:14])
except (IndexError, ValueError):
print('Skipping file', filename)
continue
try:
m = months.index(month.lower())+1
except ValueError:
print('Skipping file {} (unrecognised month)'.format(filename))
continue
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)