Open In App

Remove all empty files within a folder and subfolders in Python

Last Updated : 05 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 1

Remove 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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads