P4.4.4Batch renaming of files
Modify the program of Example E4.16 to catch the following errors and handle them gracefully:
- The user does not provide a directory name on the command line (issue a usage message);
- The directory does not exist;
- The name of a file in the directory does not have the correct format;
- The filename is in the correct format but the month abbreviation is not recognised.
Your program should terminate in the first two cases and skip the file in the second two.
Show solution
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)