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

  • 2
    Does this answer your question? [How do I remove/delete a folder that is not empty?](https://stackoverflow.com/questions/303200/how-do-i-remove-delete-a-folder-that-is-not-empty) – enzo Jun 17 '21 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. – furas Jun 17 '21 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 – Matiiss Jun 17 '21 at 22:09

1 Answers1

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?

m0g3ns
  • 44
  • 7