How to delete the contents of a folder in Python

Deleting the contents of a folder removes each file and subdirectory without deleting the folder itself.

Solution for How to delete the contents of a folder in Python : You can use os.unlink() and shutil.rmtree() to delete the contents of a folder To list all entries in a directory, call os.listdir(path) with path as the path to the desired directory. Use a for-loop to iterate over each entry in this list. In each iteration, use an if-statement to check if the current entry is a file or subdirectory. To delete a file, call os.unlink(file_path) with file_path as the path of the file to delete. To delete a subdirectory, call shutil.rmtree(file_path) with file_path as the path of the subdirectory to delete.


how-to-delete-the-contents-of-a-folder-in-python