有没有办法在Python中获取目录中的所有目录而不是文件?

发布于 2024-07-16 12:51:44 字数 166 浏览 3 评论 0原文

这个链接正在使用自定义方法,但我只是想看看是否Python 2.6 中有一个方法可以做到这一点吗?

This link is using a custom method, but I just wanna see if there is a single method to do it in Python 2.6?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

几味少女 2024-07-23 12:51:44

没有仅列出文件的内置函数,但很容易在几行中定义:

def listfiles(directory):
    return [f for f in os.listdir(directory) 
              if os.path.isdir(os.path.join(directory, f))]

编辑:已修复,谢谢 Stephan202

There isn't a built-in function to only list files, but it's easy enough to define in a couple of lines:

def listfiles(directory):
    return [f for f in os.listdir(directory) 
              if os.path.isdir(os.path.join(directory, f))]

EDIT: fixed, thanks Stephan202

人心善变 2024-07-23 12:51:44

如果a_directory是您要检查的目录,则:

next(f1 for f in os.walk(a_directory))

来自 os.walk() 参考:

通过自上而下或自下而上遍历树来生成目录树中的文件名。 对于树中以目录顶部为根的每个目录(包括顶部本身),它会生成一个 3 元组(目录路径、目录名、文件名)。

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:

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).

风流物 2024-07-23 12:51:44

我不相信有。 由于目录也是文件,因此您必须询问所有文件,然后询问每个文件是否是目录。

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.

许一世地老天荒 2024-07-23 12:51:44
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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文