我的文件结构如下所示:
我正在尝试计算整个 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 走整棵树)
pathlib
:os
.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)
将返回文件列表