簡體   English   中英

如何使用 python 刪除臨時文件?

[英]How to delete temp files using python?

所以我嘗試創建一個腳本來刪除所有下載的文件和臨時文件。 它會刪除下載的文件,但對於臨時文件,我收到了一個錯誤。


import os
import shutil

temp_dir = "C:\Windows\Temp"
downloads_dir = os.path.join(os.environ['USERPROFILE'], "Downloads")

quit = input("Do you want to delete all the downloads? (Press enter to continue)")

for file in os.listdir(downloads_dir):
    file_path = os.path.join(downloads_dir, file)
    if os.path.isdir(file_path):
        shutil.rmtree(file_path)
    else:
        os.remove(file_path)

print("All the downloaded files were deleted.")

quit = input("Do you want to delete all the temp files? (Press enter to continue)")

for file in os.listdir(temp_dir):
    file_path = os.path.join(temp_dir, file)
    if os.path.isdir(file_path):
        shutil.rmtree(file_path)
    else:
        os.remove(file_path)
        
print("All the temp files were deleted.")

這是代碼。 運行后,下載的文件被刪除,但在臨時文件中出現此錯誤:

os.remove(file_path)
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\Windows\\Temp\\DESKTOP-0CR5QUA-20221230-0000.log'

如果其他進程當前正在使用C:\Windows\Temp中的臨時文件,您將收到錯誤消息,因為刪除當前使用的文件可能會導致其他進程出錯。

如果您在嘗試執行此操作時遇到PermissionError ,只需將其包裝在 try/except 中,以便它可以繼續刪除未使用的文件的 rest 而不是使程序崩潰。

還知道刪除臨時文件,即使它們當前沒有被另一個進程打開,仍然可以查找,所以這可能會導致問題。

for file in os.listdir(temp_dir):
    file_path = os.path.join(temp_dir, file)
    try:
        if os.path.isdir(file_path):
            shutil.rmtree(file_path)
        else:
            os.remove(file_path)
    except PermissionError:
        pass

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM