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")

Output:

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")

Output:

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 argument to delete that file from the folder.

Let us see in the below example code the usage of listdir function from 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")

Output:

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.

Python - How To Delete All Files In A Directory

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.")

Output:

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 use 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.")

Output:

Delete all files and folder.

Wrap Up

I hope you were able to delete all the files in a directory using Python. Also, above method would have helped you removing all the sub-folders from the directory as well.

Let me know if you have any better method than the one discussed above in 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.

Further Read:

  1. How To Remove Non-alphanumeric Characters From String In Python
  2. How To Multiply Without Using * In Python
  3. How To Add or Append Values To a Set In Python
  4. 4 Ways To List All Subdirectories in a Directory – Python
  5. Dict To list – Convert A Dictionary to a List in Python
  6. Discord.py Bot Add Reaction To a Message Python
  7. Python Get The Minimum Value In Dictionary with Key
  8. How To Append Multiple Values To A List in Python
  9. How To Reboot or Restart Python Script

Leave a Reply

Your email address will not be published. Required fields are marked *