我有一个包含带有图像文件的文件夹的目录。我希望Python将它们的文件加起来的文件夹数返回给我,比如n
我试过的代码非常难看,包含很多循环,它给我的答案似乎不正确
import os
def countProcess(home_folder, noOfImg):
noOfDir = 0
noOfFiles = 0
for base, dirs, file in os.walk(home_folder):
dirs.sort()
for directories in dirs:
noOfDir += 1
for _, _, files in os.walk(base + '/' + directories):
for Files in files:
noOfFiles += 1
if noOfFiles == noOfImg:
return noOfDir
HOME_FOLDER = '/home/erfan/example/lfw/train'
print(countProcess(HOME_FOLDER, 100))
Wrt
您可以这样做,而不需要自己递归其他dir,因为^{} already does that
由于
True
的计算结果为1,而False
的计算结果为0,因此它可以作为一个线性函数完成:编辑:如果不想对根目录中的文件计数,请添加一个标志以排除第一个循环,该循环用于作为参数提供给
os.walk()
的根目录:这里有一个比
os.walk()
更慢的替代方法,即使用os.listdir()
的简单递归。小心使用ret_dirs=[]
它是一个可变变量,指针通过递归保持不变如果要计算仅包含n个文件的子文件夹(不包括父文件夹),请尝试此操作:
相关问题 更多 >
编程相关推荐