Generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames).
def listdirs(path):
ret = []
for cur_name in os.listdir(path):
full_path = os.path.join(path, cur_name)
if os.path.isdir(full_path):
ret.append(cur_name)
return ret
onlydirs = listdir("/tmp/")
print onlydirs
..或者作为列表理解..
path = "/tmp/"
onlydirs = [x for x in os.listdir(path) if os.path.isdir(os.path.join(path, x))]
print onlydirs
def listdirs(path):
ret = []
for cur_name in os.listdir(path):
full_path = os.path.join(path, cur_name)
if os.path.isdir(full_path):
ret.append(cur_name)
return ret
onlydirs = listdir("/tmp/")
print onlydirs
..or as a list-comprehension..
path = "/tmp/"
onlydirs = [x for x in os.listdir(path) if os.path.isdir(os.path.join(path, x))]
print onlydirs
发布评论
评论(4)
没有仅列出文件的内置函数,但很容易在几行中定义:
编辑:已修复,谢谢 Stephan202
There isn't a built-in function to only list files, but it's easy enough to define in a couple of lines:
EDIT: fixed, thanks Stephan202
如果a_directory是您要检查的目录,则:
next(f1 for f in os.walk(a_directory))
来自 os.walk() 参考:
If a_directory is the directory you want to inspect, then:
next(f1 for f in os.walk(a_directory))
From the os.walk() reference:
我不相信有。 由于目录也是文件,因此您必须询问所有文件,然后询问每个文件是否是目录。
I don't believe there is. Since directories are also files, you have to ask for all the files, then ask each one if it is a directory.
..或者作为列表理解..
..or as a list-comprehension..