我的文件夹结构如下
文件夹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)
然后我打印了 numFiles.csv。不是我想怎么做。 提前致谢!
最佳答案
因为都包含在那个文件夹中,所以你只需要搜索那个目录:
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 - 使用 Python 计算并打印子文件夹中的文件数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26651712/