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

2024-05-12 14:51:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文件夹和子文件夹的目录。我要做的是获取文件夹中子文件夹的数量,并使用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)

Tags: 文件path答案代码import目录文件夹数量
3条回答

我认为os.walk可能是你想要的:

import os

def fcount(path):
    count1 = 0
    for root, dirs, files in os.walk(path):
            count1 += len(dirs)

    return count1

path = "/home/"
print fcount(path)

这将给出给定路径中的目录数。

回答:

how would I get the number of subfolders within a folder

您可以使用类似于os.path.isfileos.path.isdir函数计算目录。

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放在最后一行,而不是注释所在的位置。

相关问题 更多 >