小编sel*_*ste的帖子

使用Python计算和打印子文件夹中的文件数

我的文件夹结构如下:
文件夹A
文件夹B1
文件夹B2
....
文件夹Bn

如何计算每个文件夹(文件夹B1-文件夹Bn)中的文件数,检查文件数是否大于给定的限制,然后在屏幕上打印文件夹名称和其中的文件数?

像这样:
文件太多的文件
夹:文件夹B3 101
文件夹B7 256

到目前为止,这是我尝试过的。它遍历我的每个文件夹B1等中的每个子文件夹。我只需要一个级别的文件计数。

import os, sys ,csv
path = '/Folder A/'

outwriter = csv.writer(open("numFiles.csv", 'w')

dir_count = []

for root, dirs, files in os.walk(path):
    for d in dirs:
        a = str(d)
        count = 0
        for fi in files:
            count += 1
        y = (a, count)
        dir_count.append(y)

    for i in dir_count:
        outwriter.writerow(i)
Run Code Online (Sandbox Code Playgroud)

然后我只打印了numFiles.csv。不完全是我想要的方式。提前致谢!

python numbers file count

2
推荐指数
1
解决办法
5405
查看次数

标签 统计

count ×1

file ×1

numbers ×1

python ×1