Python For 循环不遍历目录

Python For loop not iterating through directories

我正在尝试删除包含多个子文件夹的文件夹中两个日期之间的文件。 我想保留最新的 14 天文件,并在一个月内删除所有子文件夹中剩余的 16 个文件。 我当前的脚本正在删除第一个目录 D:\S135\firstdirectory 并在不触及剩余文件夹的情况下进入 else 块。

Error: FileNotFoundError: [WinError 2] The system cannot find the file specified: 

代码

import os
import time
import datetime

def main():
    start_date = datetime.datetime.strptime('2022-03-01', '%Y-%m-%d')
    to_delete = 'D:\S135'

    if os.path.exists(to_delete):
        if os.path.isdir(to_delete):
            for root_folder, folders, files in os.walk(to_delete):
                for file in files:
                    curpath = os.path.join(to_delete, file)
                    file_modified = datetime.datetime.fromtimestamp(os.path.getmtime(curpath))
                    if datetime.datetime.now() - file_modified > datetime.timedelta(days=14):   
                        if file_modified > start_date :
                            print(curpath)

if __name__ == "__main__":
    # invoking main function
    main()

尝试添加topdown=true

for root_folder, folders, files in os.walk(to_delete, topdown=true)

改变

                    curpath = os.path.join(to_delete, file)

                    curpath = os.path.join(root_folder, file)

因为 files 中的名称是相对于递归的当前目录,而不是您开始的文件夹。