Remove all empty files within a folder and subfolders in Python
Last Updated :
28 Apr, 2025
In this article, we will see how to remove all empty files within a folder and its subfolders in Python. We occasionally produce some empty files that are not needed. Here, we will use the below functions/methods to remove all empty files within a folder and its subfolder imported from the OS module and glob module.
Method | Description |
---|
os.walk(path) | Generates the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory, it yields a tuple with three items - dir path, dir names, and filenames. |
os.path.isfile() | Checks whether the specified path is an existing regular file or not. |
os.path.getsize() | Returns the size of the file. |
os.remove() | Remove or delete a file path from the system. |
glob.glob(pathname) | Finds all the pathnames matching a specified pattern according to the rules used by the Unix shell. |
Directory Structure
The filenames as 'empty' are empty files i.e. empty.txt, empty.png, and empty.json are empty files. Whereas main.py does contain some random Python code (non-empty file). We will use the below-mentioned directory structure for both examples:
Example Directory Structure
Remove all Empty Files using glob.glob()
Python glob module provides an ability to look for path names based on certain pattern matches. In this example, we will see how we can iterate in a path using a pattern.
- The function "delete empty files using glob()" in the code above takes a path pattern and deletes any empty files that are discovered in the iterative paths.
- The path name is followed by the pattern "\*\*" as seen in the output image, indicating that we are viewing two directory levels inside the root path.
- If it was "\*" then it would only search the top-level directory of the root path.
- Since these folders had empty files, the program destroyed them: "/Root Dir/," "/Root Dir/Dir 1/," and "/Root Dir/Dir 2/."
- Since '/Root Dir/Dir 2/Dir 2 1' is three levels lower in the directory hierarchy, it was not checked.
- This method is useful when you do not want to iterate recursively to all the directories, subdirectories, or levels.
Python3
import os
import glob
def delete_empty_files_using_glob(pathname: str):
'''
Deletes empty files from the path which matches the pattern
defined by `pathname` parameter using the glob module.
'''
no_of_files_deleted = 0
# Get the path that are matching with the pattern
files = glob.glob(pathname)
for path in files:
# Check if the path is a file and empty (size = 0)
if (
os.path.isfile(path) and
os.path.getsize(path) == 0
):
# Print the path of the file that will be deleted
print("Deleting File >>>", path.replace('\\', '/'))
# Delete the empty file
os.remove(path)
no_of_files_deleted += 1
print(no_of_files_deleted, "file(s) have been deleted.")
if __name__ == "__main__":
# Ask USER to input the path to look for
pathname = input('Enter the path: ')
# Call the function to start the delete process
delete_empty_files_using_glob(pathname)
Output:
Output - Example 1Remove Empty Files using os.walk()
Here, We first ask the user to enter the path where they want to remove the empty files. The delete_empty_files_using_walk() function takes this path as an argument and starts routing through all the possible combinations of folders, subfolders, and files for each path, it checks if the path represents a file and if it is empty. If yes, then it deletes the file. Here, The os.walk() method will look for all the folders and subfolders present until the lowest levels in the hierarchy. Therefore, we can see in the output that all the empty files at each level have been deleted by the program.
Python3
import os
def delete_empty_files_using_walk(root_path):
no_of_files_deleted = 0
# Route through the directories and files within the path -
for (dir, _, files) in os.walk(root_path):
for filename in files:
# Generate file path
file_path = os.path.join(dir, filename)
# Check if it is file and empty (size = 0) --------
if (
os.path.isfile(file_path) and
os.path.getsize(file_path) == 0
):
# Print the path of the file that will be deleted
print("Deleting File >>>", file_path.replace('\\', '/'))
# Delete the empty file
os.remove(file_path)
no_of_files_deleted += 1
print(no_of_files_deleted, "file(s) have been deleted.")
if __name__ == "__main__":
# Ask USER to input the path to look for
root_path = input('Enter the path: ')
# Call the function to start the delete process
delete_empty_files_using_walk(root_path)
Output:
Output - Example 2
Similar Reads
Python - Move all files from subfolders to main folder This article will discuss how to move all files from the subfolder to the main folder using Python. The approach is simple it is similar to moving files from one folder to another using Python, except here the main folder or parent folder of the subfolder is passed as the destination. Modules UsedOS
3 min read
How to print all files within a directory using Python? The OS module is one of the most popular Python modules for automating the systems calls and operations of an operating system. With a rich set of methods and an easy-to-use API, the OS module is one of the standard packages and comes pre-installed with Python. In this article, we will learn how to
3 min read
Python - Copy Files From Subfolders to the Main folder In this article, we will discuss how to copy a file from the subfolder to the main folder. The directory tree that will be used for explanation in this article is as shown below: D:\projects\base | |__subfolder: | \__file.txt | |__main.py | Here we have a folder named "base" in which we have a folde
4 min read
How to create a list of files, folders, and subfolders in Excel using Python ? In this article, we will learn How to create a list of Files, Folders, and Sub Folders and then export them to Excel using Python. We will create a list of names and paths using a few folder traversing methods explained below and store them in an Excel sheet by either using openpyxl or pandas module
12 min read
Python List All Files In Directory And Subdirectories Listing all files in a directory and its subdirectories is a common task in Python, often encountered in file management, data processing, or system administration. As developers, having multiple approaches at our disposal allows us to choose the most suitable method based on our specific requiremen
5 min read
Python List All Files In Directory And Subdirectories Listing all files in a directory and its subdirectories is a common task in Python, often encountered in file management, data processing, or system administration. As developers, having multiple approaches at our disposal allows us to choose the most suitable method based on our specific requiremen
5 min read