有没有一种方法可以检索 Python 中的子目录而不必遍历所有文件?

Is there a way to retrieve subdirectories in Python without having to iterate over all files?

我正在寻找一种方法来列出当前工作目录中包含的子目录,但是,我一直无法找到一种不遍历所有文件的方法。

本质上,如果我有一个包含大量文件和 2 个文件夹的文件夹,我想要一种方法可以快速 return 一个包含 2 个文件夹名称的列表,而无需扫描所有文件夹文件也是。

Python有没有办法做到这一点?

编辑:我应该澄清一下,我的问题是关于检索目录的性能。我已经知道几种获取目录的方法,但是如果工作目录中也有一堆文件,它们都会变慢。

不确定是否有任何直接的标准函数可以为您执行此操作。但是您可以为此使用 os.walk()os.walk() returns 格式的元组的每次迭代 -

(dirpath, dirnames, filenames)

其中 dirpath 是当前正在 walked 的目录,dirnames 包含 dirpath 中的目录,而 filenames 包含其中的文件。

你可以直接调用next(os.walk())得到一个目录的上述元组结果,那么那个元组中的第二个元素(索引 - 1)就是目录中的子文件夹。

代码-

direcs = next(os.walk('.'))[1]
最后的

direcs 将是当前文件夹的子文件夹列表。您还可以在其中提供其他文件夹以获取其中的文件夹列表。

没有办法只从操作系统中检索目录。您必须过滤结果。虽然,它看起来像使用 os.scandir improves performance by an order of magnitude (see benchmarks) over os.listdir and the older os.walk implementation since it avoids retrieving anything but metadata where possible. If you're using 3.5, it's already integrated into the standard library. Otherwise, it looks like you need to use the scandir 包。

过滤来自 os.scandir

的结果
ds = [e.name() for e in os.scandir('.') if e.is_dir()]

根据文档,walk 是根据 scandir 实现的,它也提供相同的加速。