使用 Python 计算和打印子文件夹中的文件数 [英] Count and print number of files in subfolders using Python

查看:31
本文介绍了使用 Python 计算和打印子文件夹中的文件数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My folder structure is as follows
Folder A
Folder B1
Folder B2
....
Folder Bn

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

How can I count the number of files in each of the folders (Folder B1 - Folder Bn), check if the number of files is larger than a given limit and print the folder name and number of files in it on the screen?

像这样:
包含过多文件的文件夹:
文件夹 B3 101
文件夹 B7 256

Like this:
Folders with too many files:
Folder B3 101
Folder B7 256

这是我迄今为止尝试过的.它遍历我的每个文件夹 B1 等中的每个子文件夹.我只需要一个级别的文件计数.

Here's what I've tried so far. It goes through every subfolder in each of my Folder B1 etc. I just need file count in one level.

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)

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

And then I just printed numFiles.csv. Not quite how I'd like to do it. Thanks in advance!

推荐答案

因为都在那个文件夹里,所以你只需要搜索那个目录:

As the are all contained in that single folder, you only need to search that directory:

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)

这篇关于使用 Python 计算和打印子文件夹中的文件数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆