I am addicted to cleaning the %temp% folder, so I went ahead and tried with pyautogui at first by making it click win + r to open run and type %temp% inside the prompt, but I think this way is faster

import os
import shutil
import subprocess
import time

def open_temp_folder():
    command = 'explorer shell:AppsFolder\\Microsoft.Windows.ShellExperienceHost_cw5n1h2txyewy!App'
    subprocess.Popen(command, shell=True)
    time.sleep(2)  # Wait for the folder to open

# Delete contents in %temp%
def delete_temp_contents():
    temp_path = os.getenv('TEMP')
    for root, dirs, files in os.walk(temp_path):
        for file in files:
            file_path = os.path.join(root, file)
            except Exception as e:
                print(f"Error deleting file {file_path}: {e}")
        for dir in dirs:
            dir_path = os.path.join(root, dir)
            except Exception as e:
                print(f"Error deleting directory {dir_path}: {e}")

if __name__ == "__main__":

1 Answer 1


Python tempfile

Python has a dedicated tempfile module and then you could have used tempfile.gettempdir() to retrieve the temp location for your environment. If you look at the relevant doc, this module looks at several environment variables in addition to TEMP and is more cross-platform. But it is important to note that it may return a fallback value, which is not necessarily what you want:

Python searches a standard list of directories to find one which the calling user can create files in. The list is:


As a last resort, the current working directory.

In your current implementation, if the env variable is not set, temp_path would return None. Your code will then crash. So you should at least check that temp_path is not None or an empty string, or unwanted behavior may occur. Deleting files in bulk can be quite dangerous. I think there has to be a railguard here, just to be sure you are not starting from / or c:\ :)

Exception handling

Exception handling is too broad here:

 except Exception as e:

When deleting files, you could realistically expect FileNotFoundError if the file no longer exists + PermissionError if the file is open by some process or access rights are insufficient. Maybe on Windows you can expect a different exception.

Note that shutil.rmtree has an argument ignore_errors:

If ignore_errors is true, errors resulting from failed removals will be ignored; if false or omitted, such errors are handled by calling a handler specified by onexc or onerror or, if both are omitted, exceptions are propagated to the caller.

So your exception handling routine may not trigger in practice here. The best way is to test, for example try deleting a folder that isn't there, or belongs to administrator and see what happens. Let me be honest with you, I haven't tested but I did check the docs while writing this review. That's the good thing about code reviews: they force you to go back read the docs to add substance to your replies.


Avoid doing this as this will shadow the built-in dir command:

for dir in dirs:

A word of caution

I think that removing all temp files indiscriminately may be undesirable, because some files must be currently used by open applications. A better approach would be to remove "old" stuff, and for this you will need to use other functions that can query file attributes. But I believe (I am a Linux user) that Windows actually has an option to clean up the temp folder automatically.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.