Как дать функции доступ к переменной во внутреннем цикле for других функций? - PullRequest
2 голосов
/ 28 апреля 2019

Программа переименовывает файлы из американского формата даты ММ-ДД-ГГГГ в европейский формат даты ДД-ММ-ГГГГ.Мне нужно как-то передать значение fileName в функции search_files в функцию rename_file, чтобы я мог изменить имя файла.Любая идея, как я могу это сделать?

Я думаю, что можно связать каждый fileName с его новым отформатированным именем и передать их в виде словаря.Я еще не пробовал, но есть ли более простой способ сделать это?

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
    rename_file(europeanName)


def breakdown_old_date(matches):
    for match in matches:
        # Get the different parts of the filename.
        beforePart = match.group(1)
        monthPart = match.group(2)
        dayPart = match.group(4)
        yearPart = match.group(6)
        afterPart = match.group(8)
    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 = dataPattern.search(fileName)
        # Skip files without a date.
        if not matchObj:
            continue
        else:
            matches.append(matchObj)
    breakdown_old_date(matches)


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)
    search_files(dataPattern)


if __name__ == "__main__":
    form_regex()

1 Ответ

0 голосов
/ 28 апреля 2019

Составьте matches список кортежей и для каждого файла, который соответствует:

matches.append((matchObj, fileName))

Затем извлеките его в breakdown_old_date, используя

fileName = match[1]

(нене забудьте изменить match.group вызовы на match[0].group) и передать его в качестве параметра на form_new_date, затем в качестве параметра на rename_file.

Кроме того, переместите вызов на form_new_datebreakdown_old_date) в цикл for, поэтому он выполняется для каждого файла, который вы хотите переместить.


(В качестве альтернативы, вместо создания matches списка кортежей, вы можете сделать его словарем.)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...