使用 Python 计算末尾目录中的文件数

Count number of files in end directories using Python

我有一个以树形结构归档的图像数据集,其中不同级别的文件夹名称是这些图像的标签,例如

/Label1
      /Label2
             /image1
             /image2
      /Label3
             /image3
/Label4
      /image4
      /image5

那我怎么计算每个结束文件夹中的图像数量。在上面的示例中,我想知道文件夹 /Label1/Label2/Label1/Label3Label4.

中有多少张图片

我检查了函数 os.walk(),但似乎没有简单的方法来计算每个单独的结束文件夹中的文件数。

谁能帮帮我,先谢谢了。

您可以使用 os.walk():

import os
c=0
print(os.getcwd())
for root, directories, filenames in os.walk('C:/Windows'):
    for files in filenames:
        c=c+1
print(c)

输出:

125765
>>> 

如果您的子目录中有多种文件格式,您可以使用运算符并检查 jpeg、png,然后递增计数器。

I checked out the function os.walk(), but it seems that there is no easy way to count number of files in each individual end folder.

当然有。只是 len(files).

我不是 100% 确定您所说的 "end directory" 是什么意思,但是如果您想跳过不是叶子的目录(即具有子目录的目录),那同样简单:if not dirs.

最后,我不知道你是否想打印计数,将它们存储在一个以路径为键的字典中,将它们加起来,或者什么,但这些都很简单,所以这里有一些代码这三个都作为示例:

total = 0
counts = {}
for root, dirs, files in os.walk(path):
    if not dirs:
        print(f'{root}: {len(files)}')
        counts[root] = len(files)
        total += len(files)