How can I delete the contents of a local folder in Python?
The current project is for Windows, but I would like to see *nix also.
Updated to only delete files and to used the
os.path.join() method suggested in the comments. If you also want to remove subdirectories, uncomment the
import os, shutil folder = '/path/to/folder' for the_file in os.listdir(folder): file_path = os.path.join(folder, the_file) try: if os.path.isfile(file_path): os.unlink(file_path) #elif os.path.isdir(file_path): shutil.rmtree(file_path) except Exception as e: print(e)
Try the shutil module
import shutil shutil.rmtree('/path/to/folder')
shutil.rmtree(path, ignore_errors=False, onerror=None)
Docstring: Recursively delete a directory tree.
ignore_errorsis set, errors are ignored; otherwise, if
onerroris set, it is called to handle the error with arguments
(func, path, exc_info)where
os.rmdir; path is the argument to that function that caused it to fail; and
exc_infois a tuple returned by
ignore_errorsis false and
None, an exception is raised.
Important Note: Be aware that
shutil.rmtree() doesn't just delete the contents of the target folder. It deletes the folder itself as well.