How to remove all empty files within a folder and its subfolders in Python?
Hello everyone, in this tutorial we are going to learn about deleting all empty files in a folder using python, This helps us in saving time as manually deleting the files take a lot of time.
Delete empty files using os library
Let’s consider a folder named sample.
The sample consists of a subfolder named “sub” and an empty text file named “empty1.txt”.The subfolder “sub” consists of another empty text file “empty2.txt”.The structure of the “sample” folder is given below:
sample-(folder)
—>empty1.txt
—>sub(folder) —> empty2.txt-(text file)
Our objective is to delete empty files in the “sample” folder and empty files in its subfolders.
Functions/Methods used in the code:
- os.walk(path)
- os.path.isfile()
- os.path.getsize()
- os.remove()
Learn more about os library OS Module in Python
CODE
import os def remove_empty(path): print(list(os.walk(path))) for (dirpath, folder_names, files) in os.walk(path): for filename in files: file_location = dirpath + '/' + filename #file location is location is the location of the file if os.path.isfile(file_location): if os.path.getsize(file_location) == 0:#Checking if the file is empty or not os.remove(file_location) #If the file is empty then it is deleted using remove method if __name__ == "__main__": path = 'C:/Users/nikk/Desktop/sample' #Location of the folder remove_empty(path) # Calling the function
Output
After executing the above code, the empty files "empty1.txt" and "empty2.txt" are deleted from the folder
Also read: Delete only empty folders in Python
Leave a Reply