计算 Python 中的子目录或文件的数量

Count the number of subdirectories or files in Python

所以我需要计算目录(递归和非递归)中的子目录数或文件数(取决于用户想要做什么)。我是用 C# 做的,但我是 Python 的新手。我发现了这个:

(len([f for f in os.listdir(directory)]))

但是这段代码计算了目录中的所有内容(文件、子目录),而我只需要子目录或文件,而不是它们在一起。有解决这个问题的功能吗? 提前感谢所有回复!

提示 os.walk

这样的事情怎么样:

import os

n_dirs = 0
n_files = 0
for root, dirs, files in os.walk(directory, topdown=False):
   n_files += len(files)
   n_dirs += len(dirs)

也许不是最优雅的解决方案,但它应该可以完成工作。 :)

递归glob可以解决:

import os
import glob

# Remove one for the root directory
print(len(glob.glob(os.path.join(directory, "**"), recursive=True)) - 1)

使用 pathlib 的 glob 方法:

from pathlib import Path

path = Path(your_path)
num_of_sub_dirs, num_of_files = 0, 0
# if you want to check inside sub-directories as well, then use path.rglob('*')
for f in path.glob('*'): 
    print(f.name)
    if f.is_dir():
        num_of_sub_dirs += 1
    if f.is_file():
        num_of_files += 1

print(num_of_sub_dirs, num_of_files)