|
| 1 | +#! python3 |
| 2 | +# renameDates.py - Renames filenames with American MM-DD-YYYY date format |
| 3 | +# to European DD-MM-YYYY. |
| 4 | + |
| 5 | +import shutil, os, re |
| 6 | + |
| 7 | +# Create a regex that matches files with the American date format. |
| 8 | +datePattern = re.compile(r"""^(.*?) # all text before the date |
| 9 | + ((0|1)?\d)- # one or two digits for the month |
| 10 | + ((0|1|2|3)?\d)- # one or two digits for the day |
| 11 | + ((19|20)\d\d) # four digits for the year (must start with 19 or 20) |
| 12 | + (.*?)$ # all text after the date |
| 13 | + """, re.VERBOSE) |
| 14 | + |
| 15 | +# Loop over the files in the working directory. |
| 16 | +for amerFilename in os.listdir('.'): |
| 17 | + mo = datePattern.search(amerFilename) |
| 18 | + |
| 19 | + # Skip files without a date. |
| 20 | + if mo == None: |
| 21 | + continue |
| 22 | + |
| 23 | + # Get the different parts of the filename. |
| 24 | + beforePart = mo.group(1) |
| 25 | + monthPart = mo.group(2) |
| 26 | + dayPart = mo.group(4) |
| 27 | + yearPart = mo.group(6) |
| 28 | + afterPart = mo.group(8) |
| 29 | + |
| 30 | + # Form the European-style filename. |
| 31 | + euroFilename = beforePart + dayPart + '-' + monthPart + '-' + yearPart + afterPart |
| 32 | + |
| 33 | + # Get the full, absolute file paths. |
| 34 | + absWorkingDir = os.path.abspath('.') |
| 35 | + amerFilename = os.path.join(absWorkingDir, amerFilename) |
| 36 | + euroFilename = os.path.join(absWorkingDir, euroFilename) |
| 37 | + |
| 38 | + # Rename the files. |
| 39 | + print('Renaming "%s" to "%s"...' % (amerFilename, euroFilename)) |
| 40 | + #shutil.move(amerFilename, euroFilename) # uncomment after testing |
0 commit comments