【问题标题】:Python - How can the script go through directories and check if there are empty or not?Python - 脚本如何遍历目录并检查是否有空?
【发布时间】:2020-06-24 10:37:11
【问题描述】:

我有一个练习来遍历子目录中的所有目录并检查是否有空目录。 我已经尝试了一些方法,但这不起作用:

import os
path = input(">>> ")

for (root,dirs,files) in os.walk(path, topdown=True):
    if len(dirs and files) == 0:
        print(os.listdir(dirs)) == 0
        print(root)
        print(dirs)
        print(files)
        print('--------------------------------')
    else:
        print()

你能帮帮我吗?

谢谢

【问题讨论】:

标签: python python-3.x directory


【解决方案1】:

你可以试试这个:

'''
    Check if a Directory is empty :
'''    
if len(os.listdir(path) ) == 0:
    print("Directory is empty")
else:    
    print("Directory is not empty")
  • 你必须导入操作系统

【讨论】:

  • 感谢您的回答。但是它不会遍历子目录中的其他文件夹。我该怎么做?
  • 您是指直接子目录,还是树下的每个目录?无论哪种方式,您都可以使用 os.walk 来执行此操作: os.walk(directory) 将为每个子目录生成一个元组。三元组中的第一个条目是目录名称,因此 [x[0] for x in os.walk(directory)] 应该递归地为您提供所有子目录。
猜你喜欢
  • 2011-05-11
  • 2013-12-07
  • 2015-01-08
  • 2018-12-23
  • 2022-11-23
  • 1970-01-01
  • 2017-02-20
  • 2012-09-22
  • 2017-08-01
相关资源
最近更新 更多