Delete all files in a directory in Python
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.
|
1 2 3 4 5 6 |
import os dir = 'path/to/dir' for f in os.listdir(dir): os.remove(os.path.join(dir, f)) |
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.
|
1 2 3 4 5 6 7 |
import os, glob dir = 'path/to/dir' filelist = glob.glob(os.path.join(dir, "*")) for f in filelist: os.remove(f) |
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.
|
1 2 3 4 5 6 |
import os, glob dir = 'path/to/dir' for file in os.scandir(dir): os.remove(file.path) |
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:
|
1 2 3 4 5 6 7 8 9 10 |
import os, shutil dir = 'path/to/dir' for files in os.listdir(dir): path = os.path.join(dir, files) try: shutil.rmtree(path) except OSError: os.remove(path) |
If you need to delete the complete directory, you can directly call the shutil.rmtree() function on the root directory:
|
1 2 3 4 5 |
import shutil dir = 'path/to/dir' shutil.rmtree(dir) |
That’s all about deleting all files in a directory in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)