【问题标题】:Listing folders in current working directory [duplicate]列出当前工作目录中的文件夹[重复]
【发布时间】:2013-02-11 09:32:06
【问题描述】:

如何在 Python 中获取当前工作目录中的文件夹列表?
我只需要文件夹,不需要文件或子文件夹。

【问题讨论】:

标签: python directory


【解决方案1】:

简单的列表理解:

[fn for fn in os.listdir(u'.') if os.path.isdir(fn)]

【讨论】:

    【解决方案2】:

    感谢@ATOzTOA
    您可以像这里一样使用os.listdiros.path.isfile

    import os
    
    path = 'whatever your path is'
    
    for item in os.listdir(path):
        if not os.path.isfile(os.path.join(path, item)):
            print "Folder: ",item
        else:
            print "File: ",item
    

    现在您知道什么是文件夹和什么是文件了。
    由于您不需要文件,您可以简单地将文件夹(路径或名称)存储在列表中
    为此,请执行以下操作:

    import os
    
    path = 'whatever your path is'
    folders = [] # list that will contain folders (path+name)
    
    for item in os.listdir(path):
        if not os.path.isfile(os.path.join(path, item)):
            folders.append(os.path.join(path, item)) #  os.path.join(path, item) is your folder path
    

    【讨论】:

    • 谢谢,这正是我需要的:)
    • @AhmetSezginDuran 添加了更多代码,请参阅。另外,请接受这个答案,它有帮助......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-07
    • 2018-06-08
    • 2012-03-20
    相关资源
    最近更新 更多