3

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

Johnathon
  • 165
  • 1
  • 1
  • 6

5 Answers5

6
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.

user1016274
  • 4,071
  • 1
  • 23
  • 19
  • The script is written in a platform-independent way (e.g. constructing the path via function and not string concatination) except for a) the names of folders to skip which in Linux at least would be ".", "..", and b) the error value returned by os.remove(). It should be raised if the file is in use, or permissions do not suffice. – user1016274 May 03 '20 at 19:19
  • Linux does not have folders callded `RECYCLER` or `RECYCLED` – alper May 04 '20 at 23:33
  • That's what I mentioned in my comment. – user1016274 May 06 '20 at 09:36
1

The for loop uses dir to find all files, but not directories, in the current directory and all subfolders recursively. Then the second line checks to see if the length of each file is less than 1 byte before deleting it.

cd /d C:\folder1

for /F "usebackq" %%A in (`dir/b/s/a-d`) do (
    if %%~zA LSS 1 del %%A
)
Marichyasana
  • 2,966
  • 1
  • 19
  • 20
1
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)  
Vaibhav S
  • 115
  • 1
  • 12
0

I do first remove empty files, afterwards by following this answer (https://stackoverflow.com/a/6215421/2402577), I have removed the empty folders.

In addition, I added topdown=False in os.walk() to walk from leaf to roo since the default behavior of os.walk() is to walk from root to leaf.

So empty folders that also contains empty folders or files are removed as well.

import os    

def remove_empty_files_and_folders(dir_path) -> None:
    for root, dirnames, files in os.walk(dir_path, topdown=False):
        for f in files:
            full_name = os.path.join(root, f)
            if os.path.getsize(full_name) == 0:
                os.remove(full_name)

        for dirname in dirnames:
            full_path = os.path.realpath(os.path.join(root, dirname))
            if not os.listdir(full_path):
                os.rmdir(full_path)
alper
  • 2,919
  • 9
  • 53
  • 102
-1

I hope this can help you

#encoding = utf-8
import os

docName = []
def listDoc(path):
    docList = os.listdir(path)
    for doc in docList:
        docPath = os.path.join(path,doc)
        if os.path.isfile(docPath):
            if os.path.getsize(docPath)==o:
                os.remove(docPath)
        if os.path.isdir(docPath):
            listDoc(docPath)

listDoc(r'C:\folder1')
jh liu
  • 62
  • 3