有没有办法在Python中返回当前目录中所有子目录的列表?
我知道您可以对文件执行此操作,但我需要获得目录列表。
有没有办法在Python中返回当前目录中所有子目录的列表?
我知道您可以对文件执行此操作,但我需要获得目录列表。
当前回答
import os
d = '.'
[os.path.join(d, o) for o in os.listdir(d)
if os.path.isdir(os.path.join(d,o))]
其他回答
您是指直接子目录,还是树下的每个目录?
无论哪种方式,你都可以使用os。走路做这个:
os.walk(directory)
将为每个子目录生成一个元组。三元组中的第一个条目是一个目录名,因此
[x[0] for x in os.walk(directory)]
应该会递归地给出所有子目录。
注意,元组中的第二个条目是第一个位置的条目的子目录列表,所以您可以使用这个代替,但它不太可能节省太多时间。
但是,你可以使用它来给你直接的子目录:
next(os.walk('.'))[1]
或者查看已经发布的其他解决方案,使用os。Listdir和os.path。isdir,包括“如何在Python中获取所有直接子目录”中的那些。
我们可以使用os.walk()来获取所有文件夹的列表
import os
path = os.getcwd()
pathObject = os.walk(path)
这个pathObject是一个对象,我们可以通过
arr = [x for x in pathObject]
arr is of type [('current directory', [array of folder in current directory], [files in current directory]),('subdirectory', [array of folder in subdirectory], [files in subdirectory]) ....]
我们可以通过遍历arr并打印中间的数组来获得所有子目录的列表
for i in arr:
for j in i[1]:
print(j)
这将打印所有子目录。
获取所有文件:
for i in arr:
for j in i[2]:
print(i[0] + "/" + j)
谢谢你们的建议,伙计们。我遇到了软链接(无限递归)作为dirs返回的问题。Softlinks吗?我们不想要臭软链接!所以…
这只是渲染dirs,而不是软链接:
>>> import os
>>> inf = os.walk('.')
>>> [x[0] for x in inf]
['.', './iamadir']
通过从这里加入多个解决方案,这是我最终使用的:
import os
import glob
def list_dirs(path):
return [os.path.basename(x) for x in filter(
os.path.isdir, glob.glob(os.path.join(path, '*')))]
虽然这个问题很久以前就有答案了。我想推荐使用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.