Python recursively delete empty files or empty directories in a directory

Idea:
Get the file name recursively, determine the file size, and delete it when the size is equal to 0. The reader can merge the two parts of the code and kill both.
1: Delete empty files

import os
def del_dir(path):
    for (root, dirs, files) in os.walk(path):
        for item in files:
            # print(root,item)
            a=os.path.join(root,item)
            print(a)
            r = os.path.getsize(a)
            if r==0:
                os.remove(a)
            try:
                pass
            except Exception as e:
                print('Exception',e)
if __name__ == '__main__':
    dir = r'./data2'
    del_dir(dir)

2: Delete empty directories

import os
def del_dir(path):
    for (root, dirs, files) in os.walk(path):
        for item in dirs:
            dir = os.path.join(root, item)
            try:
                os.rmdir(dir)  #os.rmdir() 方法用于删除指定路径的目录。仅当这文件夹是空的才可以, 否则, 抛出OSError。
                print(dir)
            except Exception as e:
                print('Exception',e)
if __name__ == '__main__':
    dir = r'F:\test'
    del_dir(dir)

Guess you like

Origin blog.csdn.net/qq_34237321/article/details/111916457