我試圖洗掉檔案夾中兩個日期之間的檔案,其中包含多個子檔案夾。我想保留最新的 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()
uj5u.com熱心網友回復:
改變
curpath = os.path.join(to_delete, file)
到
curpath = os.path.join(root_folder, file)
因為其中的名稱files是相對于遞回的當前目錄,而不是您開始的檔案夾。
uj5u.com熱心網友回復:
嘗試添加topdown=true
for root_folder, folders, files in os.walk(to_delete, topdown=true)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/454294.html
