【问题标题】:How to count total number of files in subfolders如何计算子文件夹中的文件总数
【发布时间】:2021-06-16 04:15:58
【问题描述】:

我的文件结构如下:

  • 外文件夹
    • 内文件夹 1
      • 文件...
    • 内文件夹 2
      • 文件...

我正在尝试计算整个外部文件夹中的文件总数。当我将 os.walk 传递给 Outer 文件夹时,它不会返回任何文件,因为我只有两层,所以我手动编写了它:

total = 0
folders = ([name for name in os.listdir(Outer_folder)
            if os.path.isdir(os.path.join(Outer_folder, name))])
for folder in folders:
    contents = os.listdir(os.path.join(Outer_folder, folder))
    total += len(contents)
print(total)

有更好的方法吗?我可以在任意嵌套的一组文件夹中找到文件的数量吗?我在 stackoverflow 上看不到任何深度嵌套文件夹的示例。

(我所说的“更好”是指某种内置函数,而不是手动编写一些东西来迭代 - 例如遍历整个树的 os.walk)

【问题讨论】:

标签: python pathlib


【解决方案1】:

使用pathlib:

显然你也想要这些文件:

from pathlib import Path
import numpy as np

p = Path.cwd()  # if you're running in the current dir
p = Path('path to to dir')  # pick one 

# gets all the files
f = [y for y in p.rglob(f'*')] 

# counts them
values, counts = np.unique([x.parent for x in f ], return_counts=True)

print(list(zip(counts, values)))

输出:

  • 具有计数和路径的元组列表
[(8, WindowsPath('E:/PythonProjects/stack_overflow')),
 (2, WindowsPath('E:/PythonProjects/stack_overflow/.ipynb_checkpoints')),
 (7, WindowsPath('E:/PythonProjects/stack_overflow/complete_solutions/data')),
 (3, WindowsPath('E:/PythonProjects/stack_overflow/csv_files')),
 (1,
  WindowsPath('E:/PythonProjects/stack_overflow/csv_files/.ipynb_checkpoints')),
 (5, WindowsPath('E:/PythonProjects/stack_overflow/data'))]
  • print(f) 将返回文件列表

【讨论】:

    【解决方案2】:

    我会建议你使用递归作为下面的函数:

    def get_folder_count(path):
        folders = os.listdir(path)
        folders = list(filter(lambda a: os.path.isdir(os.path.join(path, a)), folders))
        count = len(folders)
        for i in range(count):
            count += get_folder_count(os.path.join(path, folders[i]))
        return count
    

    【讨论】:

      【解决方案3】:

      这是 Blender here 建议的一种方法。 def 文件计数(文件夹): "统计一个目录下的文件个数"

      count = 0
      
      for filename in os.listdir(folder):
          path = os.path.join(folder, filename)
      
          if os.path.isfile(path):
              count += 1
          elif os.path.isfolder(path):
              count += fileCount(path)
      
      return count
      

      这被包装在一个函数中。但是您需要澄清“最佳”的含义。这是最快的吗?最易读?内存最少?

      【讨论】:

        【解决方案4】:

        我所说的“更好”是指某种内置函数,而不是手动编写一些东西来迭代 - 例如一个遍历整棵树的 os.walk

        import os
        number_of_files = sum([len(files) for r, d, files in os.walk("path/to/folder")])
        

        来源(可能重复):Return number of files in directory and subdirectory

        【讨论】:

          猜你喜欢
          • 2017-12-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-09-16
          • 2019-08-12
          • 1970-01-01
          • 2016-02-25
          • 1970-01-01
          相关资源
          最近更新 更多