如何使用Python重命名目录中的所有文件和子文件夹

2024-09-28 01:31:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用一本关于Python的书做一个小项目。其中一个例子是如何重命名根文件夹下的所有文件和目录,但是我想更进一步,更改子目录中的文件。在

我认为使用os.walk是我的最佳选择,但我只能让它更改文件名而不是子目录。我还想在执行os.walk时更改子目录名。在

我正在使用一本书和在线资源来实现这一点,任何帮助都将是了不起的。在

这是我现在根据这本书得到的。我试图包含os.listdir,但是regex不能这样工作。在

import shutil, os, re

#regex that matches files with dates
wrongFormat = re.compile(r"""^(.*?)
    ((0|1)?\d).
    ((0|1|2|3)?\d).
    ((19|20)\d\d)
    (.*?)$
    """, re.VERBOSE)
#Loop over the files in the working directory
path = '.'
for path, dirs, files in os.walk(path, topdown=True):
    for incorrectDt in files:
        dt = wrongFormat.search(incorrectDt)
#Skip file without a date
        if dt == None:
            continue
#Split filename into parts
        beforePart = dt.group(1)
        monthPart = dt.group(2)
        dayPart = dt.group(4)
        yearPart = dt.group(6)
        afterPart = dt.group(8)

#Form the new date format
        correctFormat = beforePart + monthPart + "_" + dayPart + "_" + yearPart + afterPart

#Get full, absolute file paths.
        absWorkingDir = os.path.abspath(path)
        incorrectDt= os.path.join(absWorkingDir, incorrectDt)
        correctFormat = os.path.join(absWorkingDir, correctFormat)

#rename files 
        print ('Renaming "%s" to "%s"...' % (wrongFormat, correctFormat))

        shutil.move(incorrectDt, correctFormat)


Tags: 文件thepathinreosdtgroup

热门问题