简体   繁体   中英

How to delete temp files using python?

So I tried to create a script that deletes all of your downloaded files and temp files. It deletes the downloaded files, but for the temp files I'm getting an error.


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.")

This is the code. After running it, the downloaded files are deleted but at the temp files I get this error:

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'

If other processes are currently using the temporary files in C:\Windows\Temp you'll get an error, because deleting currently used files could cause errors in those other processes.

If you get a PermissionError when you try to do this, just wrap it in a try/except so that it can continue deleting the rest of the files that aren't being used instead of crashing the program.

Also know that deleting temp files, even if they aren't currently opened by another process, could still be looked up, so that might cause issues.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM