How to delete the contents of a folder in Python?


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.

11/12/2017 9:41:14 PM

Accepted Answer

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 elif statement.

import os, shutil
folder = '/path/to/folder'
for the_file in os.listdir(folder):
    file_path = os.path.join(folder, the_file)
        if os.path.isfile(file_path):
        #elif os.path.isdir(file_path): shutil.rmtree(file_path)
    except Exception as e:
4/24/2019 10:55:54 AM

Try the shutil module

import shutil

Description: shutil.rmtree(path, ignore_errors=False, onerror=None)

Docstring: Recursively delete a directory tree.

If ignore_errors is set, errors are ignored; otherwise, if onerror is set, it is called to handle the error with arguments (func, path, exc_info) where func is os.listdir, os.remove, or os.rmdir; path is the argument to that function that caused it to fail; and exc_info is a tuple returned by sys.exc_info(). If ignore_errors is false and onerror is 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.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow