gpt4 book ai didi

python - 如何使用 Python os walks 获取子文件夹和文件夹的数量?

转载 作者:太空狗 更新时间:2023-10-30 01:41:34 26 4
gpt4 key购买 nike

我有一个文件夹和子文件夹目录。我想要做的是获取文件夹中子文件夹的数量,并使用 matplotlib 将它们绘制在散点图上。我有获取文件数量的代码,但是如何获取文件夹中子文件夹的数量。这可能有一个简单的答案,但我是 Python 的新手。感谢您的帮助。

这是我到目前为止获取文件数量的代码:

import os
import matplotlib.pyplot as plt

def fcount(path):
count1 = 0
for f in os.listdir(path):
if os.path.isfile(os.path.join(path, f)):
count1 += 1

return count1

path = "/Desktop/lay"
print fcount(path)

最佳答案

import os

def fcount(path, map = {}):
count = 0
for f in os.listdir(path):
child = os.path.join(path, f)
if os.path.isdir(child):
child_count = fcount(child, map)
count += child_count + 1 # unless include self
map[path] = count
return count

path = "/Desktop/lay"
map = {}
print fcount(path, map)

这是一个完整的实现和测试。它返回没有当前文件夹的子文件夹数。如果您想更改它,您必须将 + 1 放在最后一行而不是注释所在的位置。

关于python - 如何使用 Python os walks 获取子文件夹和文件夹的数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19747408/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com