有没有办法在Python中返回当前目录中所有子目录的列表?

我知道您可以对文件执行此操作,但我需要获得目录列表。


当前回答

虽然这个问题很久以前就有答案了。我想推荐使用pathlib模块,因为这是在Windows和Unix操作系统上工作的一种健壮的方式。

要获取特定目录下的所有路径,包括子目录:

from pathlib import Path
paths = list(Path('myhomefolder', 'folder').glob('**/*.txt'))

# all sorts of operations
file = paths[0]
file.name
file.stem
file.parent
file.suffix

etc.

其他回答

下面是基于@Blair Conrad的例子的几个简单函数

import os

def get_subdirs(dir):
    "Get a list of immediate subdirectories"
    return next(os.walk(dir))[1]

def get_subfiles(dir):
    "Get a list of immediate subfiles"
    return next(os.walk(dir))[2]

谢谢你们的建议,伙计们。我遇到了软链接(无限递归)作为dirs返回的问题。Softlinks吗?我们不想要臭软链接!所以…

这只是渲染dirs,而不是软链接:

>>> import os
>>> inf = os.walk('.')
>>> [x[0] for x in inf]
['.', './iamadir']

由于我在使用Python 3.4和Windows UNC路径时偶然发现了这个问题,下面是这个环境的一个变体:

from pathlib import WindowsPath

def SubDirPath (d):
    return [f for f in d.iterdir() if f.is_dir()]

subdirs = SubDirPath(WindowsPath(r'\\file01.acme.local\home$'))
print(subdirs)

Pathlib是Python 3.4中的新功能,它使得在不同操作系统下使用路径更加容易: https://docs.python.org/3.4/library/pathlib.html

你可以用glob。glob

from glob import glob
glob("/path/to/directory/*/", recursive = True)

不要忘记*后面的/。

在Python 2.7中,可以使用os.listdir(path)获取子目录(和文件)列表

import os
os.listdir(path)  # list of subdirectories and files