有没有办法在Python中返回当前目录中所有子目录的列表?
我知道您可以对文件执行此操作,但我需要获得目录列表。
有没有办法在Python中返回当前目录中所有子目录的列表?
我知道您可以对文件执行此操作,但我需要获得目录列表。
当前回答
我最近也遇到过类似的问题,我发现python 3.6的最佳答案(用户havlock添加的)是使用os.scandir。由于似乎没有使用它的解决方案,所以我将添加自己的解决方案。首先是一种非递归解决方案,它只列出根目录下的子目录。
def get_dirlist(rootdir):
dirlist = []
with os.scandir(rootdir) as rit:
for entry in rit:
if not entry.name.startswith('.') and entry.is_dir():
dirlist.append(entry.path)
dirlist.sort() # Optional, in case you want sorted directory names
return dirlist
递归的版本是这样的:
def get_dirlist(rootdir):
dirlist = []
with os.scandir(rootdir) as rit:
for entry in rit:
if not entry.name.startswith('.') and entry.is_dir():
dirlist.append(entry.path)
dirlist += get_dirlist(entry.path)
dirlist.sort() # Optional, in case you want sorted directory names
return dirlist
记住这一项。Path使用子目录的绝对路径。如果您只需要文件夹名称,您可以使用entry.name代替。参考os。DirEntry获取关于条目对象的其他详细信息。
其他回答
以Eli Bendersky的解决方案为基础,使用以下示例:
import os
test_directory = <your_directory>
for child in os.listdir(test_directory):
test_path = os.path.join(test_directory, child)
if os.path.isdir(test_path):
print test_path
# Do stuff to the directory "test_path"
>是要遍历的目录的路径。
你可以用glob。glob
from glob import glob
glob("/path/to/directory/*/", recursive = True)
不要忘记*后面的/。
在ipython中复制粘贴友好:
import os
d='.'
folders = list(filter(lambda x: os.path.isdir(os.path.join(d, x)), os.listdir(d)))
从打印(文件夹)输出:
['folderA', 'folderB']
import os
path = "test/"
files = [x[0] + "/" + y for x in os.walk(path) if len(x[-1]) > 0 for y in x[-1]]
我就是这么做的。
import os
for x in os.listdir(os.getcwd()):
if os.path.isdir(x):
print(x)