Renaming Files with American-Style Dates to European-Style Dates

Problem statemet:
Say your boss emails you thousands of files with American-style dates
(MM-DD-Y Y Y Y) in their names and needs them renamed to European-
style dates (DD-MM-Y Y Y Y). This boring task could take all day to do by
hand! Let’s write a program to do it instead.

Here’s what the program does:   
It searches all the filenames in the current working directory for
American-style dates.
When one is found, it renames the file with the month and day swapped
to make it European-style.


This means the code will need to do the following:
Create a regex that can identify the text pattern of American-style dates.
Call os.listdir() to find all the files in the working directory.
Loop over each filename, using the regex to check whether it has a date.
If it has a date, rename the file with shutil.move() .

#! python3# renameDates.py - Renames filenames with American MM-DD-YYYY date format# to European DD-MM-YYYY.import shutil, os, re
# Create a regex that matches files with the American date format.datePattern = re.compile(r"""^(.*?) # all text before the date((0|1)?\d)-((0|1|2|3)?\d)-((19|20)\d\d)(.*?)$""", re.VERBOSE)
# Loop over the files in the working directory.for amerFilename in os.listdir('.'):
    mo = datePattern.search(amerFilename)
# Skip files without a date.if mo == None:
    continue# Get the different parts of the filename.beforePart = mo.group(1)
monthPart = mo.group(2)
dayPart= mo.group(4)
yearPart= mo.group(6)
afterPart = mo.group(8)
# Form the European-style filename.euroFilename = beforePart + dayPart + '-' + monthPart + '-' + yearPart +afterPart
# Get the full, absolute file paths.absWorkingDir = os.path.abspath('.')
amerFilename = os.path.join(absWorkingDir, amerFilename)
euroFilename = os.path.join(absWorkingDir, euroFilename)
# Rename the files.print('Renaming "%s" to "%s"...' % (amerFilename, euroFilename))
#hutil.move(amerFilename, euroFilename)

0 comments:

Post a Comment

My Instagram