【问题标题】:count number of folders with given name计算具有给定名称的文件夹数
【发布时间】:2014-07-29 18:23:18
【问题描述】:

我正在寻找具有给定名称的文件夹和子文件夹的数量...在这里我正在搜索名为“L-4”的子文件夹的数量?返回零,我确定那不是真的?我错过了什么?

import os

path = "R:\\"

i = 0
for (path, dirs, files) in os.walk(path):
    if os.path.dirname == "L-4":
        i += 1

print i

【问题讨论】:

    标签: python path operating-system


    【解决方案1】:

    os.path.dirname 是对the standard library function 的引用,而不是字符串。也许你想在这里使用os.path.dirname(path)

    您可以改为计算L-4dirs 列表中出现的次数:

    i = 0
    for root, dirs, files in os.walk(path):
        i += dirs.count('L-4')
    print i
    

    或者,作为单行:

    print sum(dirs.count('L-4') for _, dirs, _ in os.walk(path))
    

    【讨论】:

    • 你没有错过单行中的方括号吗?
    • @miindlek:不,是generator expression
    • 谢谢 Martijn。这正是我想要的!
    猜你喜欢
    • 1970-01-01
    • 2013-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-04
    • 2010-12-28
    • 1970-01-01
    相关资源
    最近更新 更多