计算具有指定名称的文件夹数量
我想统计一下某个名字的文件夹和子文件夹的数量……我在找名为“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
1 个回答
1
os.path.dirname
是一个指向 标准库函数 的引用,而不是一个字符串。也许你想在这里使用 os.path.dirname(path)
。
你可以计算一下 L-4
在 dirs
列表中出现了多少次:
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))