如何计算子文件夹中的文件总数

TIF*_*TIF 1 python pathlib

我的文件结构如下所示:

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

我正在尝试计算整个 Outer 文件夹中的文件总数。当我将 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)
Run Code Online (Sandbox Code Playgroud)

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

(“更好”我的意思只是某种内置函数,而不是手动编写一些东西来迭代 - 例如一个 os.walk 走整棵树)

Tre*_*ney 5

使用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)))
Run Code Online (Sandbox Code Playgroud)

输出:

  • 带有计数和路径的元组列表
[(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'))]
Run Code Online (Sandbox Code Playgroud)
  • print(f) 将返回文件列表