有没有办法在Python中返回当前目录中所有子目录的列表?
我知道您可以对文件执行此操作,但我需要获得目录列表。
有没有办法在Python中返回当前目录中所有子目录的列表?
我知道您可以对文件执行此操作,但我需要获得目录列表。
当前回答
你可以用glob。glob
from glob import glob
glob("/path/to/directory/*/", recursive = True)
不要忘记*后面的/。
其他回答
使用OS walk
sub_folders = []
for dir, sub_dirs, files in os.walk(test_folder):
sub_folders.extend(sub_dirs)
这应该可以工作,因为它还创建了一个目录树;
import os
import pathlib
def tree(directory):
print(f'+ {directory}')
print("There are " + str(len(os.listdir(os.getcwd()))) + \
" folders in this directory;")
for path in sorted(directory.glob('*')):
depth = len(path.relative_to(directory).parts)
spacer = ' ' * depth
print(f'{spacer}+ {path.name}')
这应该列出使用pathlib库的文件夹中的所有目录。path.relative_to(目录)。Parts获取相对于当前工作目录的元素。
虽然这个问题很久以前就有答案了。我想推荐使用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.
您是指直接子目录,还是树下的每个目录?
无论哪种方式,你都可以使用os。走路做这个:
os.walk(directory)
将为每个子目录生成一个元组。三元组中的第一个条目是一个目录名,因此
[x[0] for x in os.walk(directory)]
应该会递归地给出所有子目录。
注意,元组中的第二个条目是第一个位置的条目的子目录列表,所以您可以使用这个代替,但它不太可能节省太多时间。
但是,你可以使用它来给你直接的子目录:
next(os.walk('.'))[1]
或者查看已经发布的其他解决方案,使用os。Listdir和os.path。isdir,包括“如何在Python中获取所有直接子目录”中的那些。
在ipython中复制粘贴友好:
import os
d='.'
folders = list(filter(lambda x: os.path.isdir(os.path.join(d, x)), os.listdir(d)))
从打印(文件夹)输出:
['folderA', 'folderB']