如何删除文件夹及其子文件夹中的所有空文件?

2024-04-24 04:17:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试删除文件夹中的所有空文件,并且文件夹中存在文件夹,因此它也需要检查这些文件夹中的内容:

例如 删除C:\folder1\folder1和C:\folder1\folder2等中的所有空文件


Tags: 文件文件夹内容folder2folder1
3条回答
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

这将与一些调整一起工作:
os.remove()语句可能会失败,因此您可能也想用try...except来包装它。WindowsError是特定于平台的。严格来说,过滤遍历的目录不是必需的,而是有帮助的。

for循环使用dir递归地查找当前目录和所有子文件夹中的所有文件,但不查找目录。然后第二行在删除之前检查每个文件的长度是否小于1字节。

cd /d C:\folder1

for /F "usebackq" %%A in (`dir/b/s/a-d`) do (
    if %%~zA LSS 1 del %%A
)
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)  

相关问题 更多 >