-2

I want to clean a folder filled with files without deleting the folder and I cant for the hecc of it figure it our or find some documentation on the matter. (clearing the Temp folder filled with junk files and folders)

import os

os.remove(r"C:\Users\junio\AppData\Local\Temp\")

any suggestions to make it work? (probably pretty easy, and thanks in advance)

3
  • 2
    Does this answer your question? How do I remove/delete a folder that is not empty? Commented Jun 17, 2021 at 21:40
  • you have get all files and subfolder and delete elements one-by-one. OR delete this folder and later create it again. Commented Jun 17, 2021 at 21:44
  • You can also try this which is as far as I know windows only but should work: os.system('rmdir /s /q "%temp%"') obviously You can format the string and add other directories, this is just the shortest way to get to Temp Commented Jun 17, 2021 at 22:09

1 Answer 1

1
    import os, shutil
    folder = '/path/to/folder'
    for filename in os.listdir(folder):
        file_path = os.path.join(folder, filename)
        try:
            if os.path.isfile(file_path) or os.path.islink(file_path):
                os.unlink(file_path)
            elif os.path.isdir(file_path):
                shutil.rmtree(file_path)
        except Exception as e:
            print('Failed to delete %s. Reason: %s' % (file_path, e))

Taken from How to delete the contents of a folder?

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.