How To Give A Function Access To A Variable In Another Functions's Inner For Loop?

- 1 answer

The program renames the files from American MM-DD-YYYY date format to European DD-MM-YYYY date format. I need somehow to pass the value of fileName in search_files function to the rename_file function so I can change the name of the file. Any idea how can I do that?

I think it may be possible to associate every fileName with it's new formatted name and to pass them as a dictionary. I didn't try this yet, but is there an easier way to do that?

def rename_file(europeanName):
    # Get the full, absolute file paths.
    currentPath = os.path.abspath('.')
    fileName = os.path.join(currentPath, fileName)
    europeanName = os.path.join(currentPath, europeanName)

    # Rename the files.
    shutil.move(fileName, europeanName)

def form_new_date(beforePart, monthPart, dayPart, yearPart, afterPart):
    # Form the European-style filename.
    europeanName = beforePart + dayPart + '-' + monthPart + '-' + yearPart + afterPart

def breakdown_old_date(matches):
    for match in matches:
        # Get the different parts of the filename.
        beforePart =
        monthPart =
        dayPart =
        yearPart =
        afterPart =
    form_new_date(beforePart, monthPart, dayPart, yearPart, afterPart)

def search_files(dataPattern):
    matches = []
    # Loop over the files in the working directory.
    for fileName in os.listdir('.'):
        matchObj =
        # Skip files without a date.
        if not matchObj:

def form_regex():
    # Create a regex that can identify the text pattern of American-style dates.
    dataPattern = re.compile(r"""
        ^(.*?)                              # all text before the date
        ((0|1)?\d)-                         # one or two digits for the month
        ((0|1|2|3)?\d)-                     # one or two digits for the day
        ((19|20)\d\d)                       # four digits for the year
        (.*?)$                              # all text after the date
        """, re.VERBOSE)

if __name__ == "__main__":


Make matches a list of tuples, and for each file that matches:

matches.append((matchObj, fileName))

Then extract it out in breakdown_old_date using

fileName = match[1]

(don't forget to change your calls to match[0].group), and pass it as a parameter to form_new_date, then as a parameter to rename_file.

Also, move the call to form_new_date (in breakdown_old_date) into the for loop, so it executes for each file you want to move.

(Alternatively, instead of making matches a list of tuples, you could make it a dictionary.)