Python 如何让一个函数访问另一个函数中的变量';什么是内循环?

Python 如何让一个函数访问另一个函数中的变量';什么是内循环?,python,scope,Python,Scope,程序将文件从美国MM-DD-YYYY日期格式重命名为欧洲DD-MM-YYYY日期格式。我需要将search\u files函数中fileName的值传递给rename\u file函数,以便更改文件名。知道我该怎么做吗 我认为可以将每个文件名与其新的格式化名称关联起来,并将它们作为字典传递。我还没试过,但有没有更简单的方法 def rename_file(europeanName): # Get the full, absolute file paths. currentPath

程序将文件从美国MM-DD-YYYY日期格式重命名为欧洲DD-MM-YYYY日期格式。我需要将
search\u files
函数中
fileName
的值传递给
rename\u file
函数,以便更改文件名。知道我该怎么做吗

我认为可以将每个
文件名
与其新的格式化名称关联起来,并将它们作为字典传递。我还没试过,但有没有更简单的方法

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

使
匹配
一个元组列表,对于匹配的每个文件:

matches.append((matchObj, fileName))
然后在
分解旧数据中使用

fileName = match[1]
(别忘了更改您的
匹配。group
调用
匹配[0]。group
),并将其作为参数传递到
form\u new\u date
,然后作为参数传递到
rename\u file

另外,将对
form_new_date
(在
breakdown_old_date
中)的调用移动到for循环中,以便对要移动的每个文件执行该调用


(或者,您可以将其设置为字典,而不是将
匹配设置为元组列表。)