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

sel*_*ste 2 python numbers file count

我的文件夹结构如下:
文件夹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。不完全是我想要的方式。提前致谢!

Pad*_*ham 5

由于都包含在该单个文件夹中,因此您只需要搜索该目录:

import os
path = '/Folder A/'
mn = 20
folders = ([name for name in os.listdir(path)
            if os.path.isdir(os.path.join(path, name)) and name.startswith("B")]) # get all directories 
for folder in folders:
    contents = os.listdir(os.path.join(path,folder)) # get list of contents
    if len(contents) > mn: # if greater than the limit, print folder and number of contents
        print(folder,len(contents)
Run Code Online (Sandbox Code Playgroud)