Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove all empty files within folder and its sub folders?

Tags:

python

I am trying to remove all empty files in a folder, and there are folders within the folder so it needs to check inside those folders too:

e.g remove all empty files within C:\folder1\folder1 and C:\folder1\folder2 etc

like image 233
Johnathon Avatar asked Oct 22 '25 04:10

Johnathon


2 Answers

import sys
import os

def main():
    getemptyfiles(sys.argv[1])


def getemptyfiles(rootdir):
    for root, dirs, files in os.walk(rootdir):
        for d in ['RECYCLER', 'RECYCLED']:
            if d in dirs:
                dirs.remove(d)

        for f in files:
            fullname = os.path.join(root, f)
            try:
                if os.path.getsize(fullname) == 0:
                    print fullname
                    os.remove(fullname)
            except WindowsError:
                continue

This will work with a bit of adjusting:
The os.remove() statement could fail so you might want to wrap it with try...except as well. WindowsError is platform specific. Filtering the traversed directories is not strictly necessary but helpful.

like image 87
user1016274 Avatar answered Oct 23 '25 20:10

user1016274


import os    
while(True):
    path = input("Enter the path")  
    if(os.path.isdir(path)):  
        break  
    else:  
        print("Entered path is wrong!") 
for root,dirs,files in os.walk(path):  
    for name in files:  
        filename = os.path.join(root,name)   
        if os.stat(filename).st_size == 0:  
            print(" Removing ",filename)  
            os.remove(filename)  
like image 20
Vaibhav S Avatar answered Oct 23 '25 20:10

Vaibhav S



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!