How to delete temp files using python?

Question:

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:WindowsTemp"
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'
Asked By: Seven Whale

||

Answers:

If other processes are currently using the temporary files in C:WindowsTemp 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
Answered By: Samathingamajig
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.