How to Delete the Contents of a Folder in Python

Created
Modified

Using rmtree Method

The shutil.rmtree() method deletes an entire directory tree; path must point to a directory. For example,

#!/usr/bin/python3

# Import module
import os, shutil

def remove_dir(path):

  for filename in os.listdir(path):
    filepath = os.path.join(path, filename)
    try:
      if os.path.isfile(filepath) or os.path.islink(filepath):
        os.unlink(filepath)
      elif os.path.isdir(filepath):
        shutil.rmtree(filepath)
    except Exception as e:
      print(e)

remove_dir("abcde")

Using glob Method

You can simply do this:

#!/usr/bin/python3

# Import module
import os, glob

files = glob.glob('abcde/*')
# files = glob.glob('abcde/*.txt')

for f in files:
  os.remove(f)

Related Tags