Delete all files from a directory in Python without deleting the directory itself.

In the previous post, we have discussed how to remove a file in Python using the os.remove(), os.unlink(), and pathlib.Path.unlink() functions. This post will discuss how to remove all files from a directory.

1. Using os.listdir() function

The idea is to iterate over all files in a directory is using os.listdir() function and delete each file encountered with os.remove() function. Note this deletes all files present in the root directory but raises an exception if the directory contains any subdirectories.

Download Code

2. Using glob.glob() function

You can also iterate over files in a directory using the glob.glob function, which returns an iterator over paths that matches the specified pattern. However, this also raises an exception if the root directory has any subdirectories.

Download Code

3. Using os.scandir() function

With Python version 3.5, the faster os.scandir() function is the recommended way to iterate over files in a directory. Like all other approaches, this fails when the root directory contains subdirectories.

Download Code

4. Using shutil.rmtree() function

If you need to delete all files, subdirectories, and symbolic links from a directory, consider using the shutil.rmtree() function with the os.remove() function, as shown below:

Download Code

 
If you need to delete the complete directory, you can directly call the shutil.rmtree() function on the root directory:

Download Code

That’s all about deleting all files in a directory in Python.