- Python Delete All Files in a Folder
- Creating the Directory Structure
- Delete All Files using the OS Module
- Delete All Files using the Pathlib Module
- Delete All Files and Subfolders using the Shutil Module
- About The Python Tutorials Blog
- Python – How To Delete All Files In A Directory
- 1. Using Glob and OS with Remove Method to Delete all files in a directory
- 2. Using scandir and remove Method from OS Library
- 3. Using listdir Function from OS Library
- 4. Using Pathlib Library To Delete the Files
- 5. Using Pathlib and shutil To Delete Files and Folder Recursively
- Wrap Up
Python Delete All Files in a Folder
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())
['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.
['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 .
['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.
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.
Get Our Python Developer Kit for Free
I put together a Python Developer Kit with over 100 pre-built Python scripts covering data structures, Pandas, NumPy, Seaborn, machine learning, file processing, web scraping and a whole lot more — and I want you to have it for free. Enter your email address below and I’ll send a copy your way.
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")
Get Our Python Developer Kit for Free
I put together a Python Developer Kit with over 100 pre-built Python scripts covering data structures, Pandas, NumPy, Seaborn, machine learning, file processing, web scraping and a whole lot more — and I want you to have it for free. Enter your email address below and I’ll send a copy your way.
About The Python Tutorials Blog
The Python Tutorials Blog was created by Ryan Wells, a Nuclear Engineer and professional VBA Developer. After launching his VBA Tutorials Blog in 2015, he designed some VBA Cheat Sheets, which have helped thousands learn to write better macros. He expanded in 2018 with The Python Tutorials Blog to teach people Python in a similar systematic way. Today, wellsr.com reaches over 2 million programmers each year!
Python – How To Delete All Files In A Directory
Do you want to delete all files In a Directory if exist? This article will show you how you can delete all the files or folders in a directory using Python.
There are basically two approaches that you can follow one is using the OS library that provides you the feature to delete the files and folder in a directory. Another one is the glob library with OS library that also provides the same feature but requires lesser code.
Let us see in the below example code the usage of methods and library required to delete all the files in Python.
1. Using Glob and OS with Remove Method to Delete all files in a directory
The glob library can get you the path for all the files and folders present in a given directory from where you want to delete the files and then you can use the path in the remove() method as an argument to delete the files permanently from your computer.
Let us see in the below example code for usage of Glob and OS with Remove.
#importing Glob and OS Library import glob import os #Initializing the Folder Path folderPath = "C:\Test2" #Getting List of All the Files in the Folder filesList = glob.glob(folderPath + "\*") for file in filesList: print("Removing File <>".format(file)) os.remove(file) print("All Files are Remove if Existed")
Removing File C:\Test2\Test File 1.jpg Removing File C:\Test2\Test File 2.jpg Removing File C:\Test2\Test File 3.jpg Removing File C:\Test2\Test File 4.jpg Removing File C:\Test2\Test File 5.bin Removing File C:\Test2\Test File 6.jpeg Removing File C:\Test2\Test File 7.bin Removing File C:\Test2\Test File 8.heic All Files are Remove if Existed
2. Using scandir and remove Method from OS Library
In the OS library, the scandir function can be used to get the path for all the files present in the folder and once you have the actual path of all the files then you can easily use the remove function to delete the files from the directory.
Let us see in the below example code the usage of scandir and remove method.
#importing Glob and OS Library import os #Initializing the Folder Path folderPath = "C:\Test2" #Getting List of All the Files in the Folder for file in os.scandir(folderPath): fullFilePath = folderPath + "\\" + file.name print("Removing or Deleting the File <>".format(file.name)) os.remove(fullFilePath) print("All Files are Remove if Existed")
Removing or Deleting the File Test File 1.jpg Removing or Deleting the File Test File 2.jpg Removing or Deleting the File Test File 3.jpg Removing or Deleting the File Test File 4.jpg Removing or Deleting the File Test File 5.bin Removing or Deleting the File Test File 6.jpeg Removing or Deleting the File Test File 7.bin Removing or Deleting the File Test File 8.heic All Files are Remove if Existed
3. Using listdir Function from OS Library
You can also use the listdir() method to get the full path for the files present in the folder and then pass that full path of each file to remove() function as an argument to delete that file from the folder.
Let us see in the below example code the usage of the listdir function from the OS library.
#importing OS Library import os #Initializing the Folder Path folderPath = "C:\Test2" #Getting List of All the Files in the Folder for file in os.listdir(folderPath): fullFilePath = folderPath + "\\" + file print("Removing or Deleting the File <>".format(file)) os.remove(fullFilePath) print("All Files are Remove if Existed")
Removing or Deleting the File Test File 1.jpg Removing or Deleting the File Test File 2.jpg Removing or Deleting the File Test File 3.jpg Removing or Deleting the File Test File 4.jpg Removing or Deleting the File Test File 5.bin Removing or Deleting the File Test File 6.jpeg Removing or Deleting the File Test File 7.bin Removing or Deleting the File Test File 8.heic All Files are Remove if Existed
As you saw in the above code listdir function provided the filenames present in the folder and then we created the full path of those files and provided that path to the remove function to get the file deleted.
4. Using Pathlib Library To Delete the Files
You can also use the Pathlib library present in Python that provides the features to remove the files from the folder. You can easily delete the files using this library in one line of code. Let us see in the below example code the usage of Pathlib.
#importing Pathlib from pathlib import Path #Initializing the Folder Path folderPath = "C:\Test2" #Deleting the Files from Folder [file.unlink() for file in Path(folderPath).iterdir() if file.is_file()] #Printing that Deletion is Completed print("All files are deleted.")
5. Using Pathlib and shutil To Delete Files and Folder Recursively
If you want to delete the files and folder recursively then you need to use the Pathlib and shutil library from Python. This code will delete the sub-folders as well recursively including the files. Let us see in the below code the usage of Pathlib and Shutil in Python.
#importing Pathlib and shutil from pathlib import Path from shutil import rmtree #Initializing the Folder Path folderPath = "C:\Test2" #Deleting the Files from Folder for currentPath in Path(folderPath).iterdir(): if currentPath.is_file(): currentPath.unlink() elif currentPath.is_dir(): rmtree(currentPath) #Printing that Deletion is Completed print("Delete all files and folder.")
Delete all files and folder.
Wrap Up
I hope you were able to delete all the files in a directory using Python. Also, the above method would have helped you remove all the sub-folders from the directory as well.
Let me know if you have any better method than the one discussed above in the comment section. I will be happy to add it here.
If you liked the above tutorial then please follow us on Facebook and Twitter. Let us know the questions and answer you want to cover in this blog.