【问题标题】:Looping through many folders循环遍历多个文件夹
【发布时间】:2018-01-05 13:34:13
【问题描述】:

我必须遍历多个文件夹,最后检查最终文件夹中是否有三个文件夹。 如果文件夹中存在三个文件夹,则什么也不做,否则打印文件夹路径或名称。我发现很难让它工作, 欢迎任何建议,提前谢谢

这是我目前拥有的,

check_empty =['One','Two','Three']
path = '/mnt/sdc1/Username/'
folders = next(os.walk('/mnt/sdc1/Mahajan/'))[1]
for folder in folders:
    files_in_folders = os.listdir(path +folder)
    for files_in in files_in_folders:
        for files in os.listdir(path+folder+'/'+files_in):
            for items in check_empty:
               if files in check_empty:
                    print(folder +'Good')
               else:
                    print(folder+'NotGood')

【问题讨论】:

  • 对于这个特定的用例我可能是错的,但我通过经验和讲座了解到,通常,当你在 python 中有超过 2 个嵌套循环时,你做错了。
  • 那么,如果我从一张白纸开始,我该如何处理呢?
  • 您应该考虑使用glob.glob 或os.walk。
  • 好的,谢谢。

标签: python


【解决方案1】:

os.walk 已经为您提供了获取文件夹中所有文件的能力:

check_empty = set(check_empty)  # set is faster for simple check in unique items
for root, dirs, files in os.walk('/mnt/sdc1/Mahajan/'):
    for file in files:
        filename = os.path.basename(file)
        if filename in check_empty:
            print(root + 'Good')
        else:
            print(root + 'NotGood')

【讨论】:

  • 让我试试这个
  • 我得到的模块没有属性basename!,任何提示
  • 抱歉,请尝试改用os.path.basename
猜你喜欢
  • 2012-10-11
  • 1970-01-01
  • 1970-01-01
  • 2019-07-21
  • 2019-01-03
  • 2018-01-15
  • 2021-10-16
  • 1970-01-01
  • 2019-04-11
相关资源
最近更新 更多