有没有办法在Python中返回当前目录中所有子目录的列表?
我知道您可以对文件执行此操作,但我需要获得目录列表。
有没有办法在Python中返回当前目录中所有子目录的列表?
我知道您可以对文件执行此操作,但我需要获得目录列表。
当前回答
这个答案似乎并不存在。
directories = [ x for x in os.listdir('.') if os.path.isdir(x) ]
其他回答
我就是这么做的。
import os
for x in os.listdir(os.getcwd()):
if os.path.isdir(x):
print(x)
我更喜欢使用滤镜(https://docs.python.org/2/library/functions.html#filter),但这只是个人喜好问题。
d='.'
filter(lambda x: os.path.isdir(os.path.join(d, x)), os.listdir(d))
以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"
>是要遍历的目录的路径。
只列出目录
print("\nWe are listing out only the directories in current directory -")
directories_in_curdir = list(filter(os.path.isdir, os.listdir(os.curdir)))
print(directories_in_curdir)
只列出当前目录中的文件
files = list(filter(os.path.isfile, os.listdir(os.curdir)))
print("\nThe following are the list of all files in the current directory -")
print(files)
对于像我这样只需要一个目录中直接文件夹名称的人来说,这在Windows上是可行的。
import os
for f in os.scandir(mypath):
print(f.name)