This tutorial shows you how to delete all files in a folder using Python. In Python, the OS module allows you to delete a single file using the remove() method. Surprisingly, there’s no default support for deleting all files inside a directory in the Python OS module so we’ll walk through several strategies to help you do it. We’ll demonstrate deleting all files in a folder using the OS module, the Pathlib module and Shutil module of Python.

Creating the Directory Structure

Let’s first create some dummy files in a directory. We’ll study how to remove these files in the next sections. The following script first changes the current working directory for your Python script and populates the directory with 5 files of different types. Our dummy files will be in the C:\main directory folder. You can change this path for your specific project.

import os
os.chdir(r"C:\main directory")
wd = os.getcwd()
all_files = ['IMDB Dataset.csv', 'invoice.txt', 'movie_dataset.csv', 'panda.png', 'receipt.png']
for f in all_files:
    file = open(f, 'w+')
    file.close()

print(os.listdir())

Output:

['IMDB Dataset.csv', 'invoice.txt', 'movie_dataset.csv', 'panda.png', 'receipt.png']

Delete All Files using the OS Module

The most basic method of deleting all files in a folder is by iterating through all the file paths and deleting them one by one. The os.listdir() method returns a list containing paths of all the files in a directory. You can then use a for loop to iterate through the path list and delete each file one by one using the remove() method.

Here’s how you would do that:

import os
os.chdir(r"C:\main directory")
all_files = os.listdir()

for f in all_files:
    os.remove(f)

print(os.listdir())

The empty list in the output shows that all files were removed from our working directory.

[]

In addition to using the for loop you can also use list comprehension to remove all files from a folder, like we do in the following script:

import os
os.chdir(r"C:\main directory")
[os.remove(f) for f in os.listdir()]
print(os.listdir())

If you want to remove specific file types, you can use the endswith() method and pass it the file extension while removing files. The script below will remove all files with .png extension, and it will keep all the other files intact.

import os
os.chdir(r"C:\main directory")
[os.remove(f) for f in os.listdir() if f.endswith(".png")]
print(os.listdir())

The output below confirms all the PNG files were removed and all the other files still remain.

Output:

['IMDB Dataset.csv', 'invoice.txt', 'movie_dataset.csv']

You’ll often see situations where a folder contains both files and sub-folders. If you want to remove files but keep the subfolders, you can check the path type using the isfile() method from the os module.

Let’s first create some dummy files and folders (directories) inside our current working directory.

import os
os.chdir(r"C:\main directory")
all_files = ['IMDB Dataset.csv', 'invoice.txt', 'movie_dataset.csv', 'panda.png', 'receipt.png']
for f in all_files:
    file = open(f, 'w+')
    file.close()

os.mkdir("dir1")
os.mkdir("dir2")

print(os.listdir())

Your current working directory now contains 5 files and 2 folders, dir1 and dir2.

Output:

['dir1', 'dir2', 'IMDB Dataset.csv', 'invoice.txt', 'movie_dataset.csv', 'panda.png', 'receipt.png']

The following script uses the isfile() method to check if the path points to a file or not, the file is only deleted if the isfile() method returns true.

import os
os.chdir(r"C:\main directory")
[os.remove(f) for f in os.listdir() if os.path.isfile(f)]
print(os.listdir())

The output shows that all files are removed and only folders are left in your current working directory. Any files in those subfolders remain, as well.

Output:

['dir1', 'dir2']

To delete empty subfolders, you can iterate through the path list and use the rmdir() method. Here’s an example:

import os
os.chdir(r"C:\main directory")
[os.rmdir(f) for f in os.listdir()]
print(os.listdir())

Keep in mind that, just like with shell commands on a terminal, rmdir only works if the subfolders are empty.


Code More, Distract Less: Support Our Ad-Free Site

You might have noticed we removed ads from our site - we hope this enhances your learning experience. To help sustain this, please take a look at our Python Developer Kit and our comprehensive cheat sheets. Each purchase directly supports this site, ensuring we can continue to offer you quality, distraction-free tutorials.


Delete All Files using the Pathlib Module

The OS module isn’t the only way to remove files from a directory. You can also use the Pathlib module’s Path class to remove all files from a folder. Here’s how it works.

First, you have to create an object of the Path class and pass it your parent folder path containing all your files.

Next, you need to call the glob() method of the Path class object and pass it the type of file you want removed. The glob() method returns a list containing paths of files and folders inside a parent folder. Passing "*" to the glob() method returns all files.

Finally, you can iterate through the list returned by the glob() method and remove files using the unlink() method. You’re able to check if a path points to a file via the is_file() method. The following script removes all files from the path C:\main directory, but keeps files in subfolders.

from pathlib import Path
path = Path(r"C:\main directory")
path_list = path.glob("*")
[f.unlink() for f in path_list if f.is_file()]

Just like we did with the OS module, you can specify file types as parameter values of the glob() method. As an example, the following script only removes the PNG type files.

from pathlib import Path
[f.unlink() for f in Path(r"C:\main directory").glob("*.png") ]

Delete All Files and Subfolders using the Shutil Module

Finally, if you want to delete all files and directories, including subfolders, you can use the rmtree() method from the Shutil module. The following script removes the directory C:\main directory and all its files, folders, and subfolders.

import shutil
shutil.rmtree(r"C:\main directory")

Since, the rmtree() method removes the parent folder too, you can call mkdir() method from the OS module and pass it the path to your parent folder to create an empty folder of the same name. Here’s an example:

import shutil, os
shutil.rmtree(r"C:\main directory")
os.mkdir(r"C:\main directory")
os.listdir(r"C:\main directory")

Code More, Distract Less: Support Our Ad-Free Site

You might have noticed we removed ads from our site - we hope this enhances your learning experience. To help sustain this, please take a look at our Python Developer Kit and our comprehensive cheat sheets. Each purchase directly supports this site, ensuring we can continue to offer you quality, distraction-free tutorials.