How to delete the contents of a folder? How to delete the contents of a folder? python python

How to delete the contents of a folder?

import os, shutilfolder = '/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))

You can simply do this:

import osimport globfiles = glob.glob('/YOUR/PATH/*')for f in files:    os.remove(f)

You can of course use an other filter in you path, for example : /YOU/PATH/*.txt for removing all text files in a directory.

You can delete the folder itself, as well as all its contents, using shutil.rmtree:

import shutilshutil.rmtree('/path/to/folder')
shutil.rmtree(path, ignore_errors=False, onerror=None)

Delete an entire directory tree; path must point to a directory (but not a symbolic link to a directory). If ignore_errors is true, errors resulting from failed removals will be ignored; if false or omitted, such errors are handled by calling a handler specified by onerror or, if that is omitted, they raise an exception.