Программа переименовывает файлы из американского формата даты ММ-ДД-ГГГГ в европейский формат даты ДД-ММ-ГГГГ.Мне нужно как-то передать значение 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()