【问题标题】:How do I display the names of all the subdirectories inside a directory, without using a loop in Python? [closed]如何在不使用 Python 循环的情况下显示目录中所有子目录的名称? [关闭]
【发布时间】:2021-04-24 12:19:16
【问题描述】:

我尝试过os.listdir(),但它显示了所有文件和目录。我尝试了其他解决方案,但它们大多需要循环,我正在寻找不使用循环的方法。

【问题讨论】:

标签: python directory


【解决方案1】:

使用os.walk

import os
subdirs = next(os.walk('.'))[1]
print(subdirs)

【讨论】:

    【解决方案2】:

    和我一起工作:

    import os
    
    os.mkdir('f')
    os.mkdir(r'f/file1')
    os.mkdir(r'f/file2')
    os.mkdir(r'f/file3')
    
    os.mkdir('f/file1/abc')
    os.mkdir('f/file2/def')
    os.mkdir('f/file3/ghi')
    
    os.listdir('f')
    

    OT:

    ['file2', 'file3', 'file1']
    

    带有文件的列表目录

    os.listdir('f/file1')
    

    OT:

    ['abc']
    

    【讨论】:

      猜你喜欢
      • 2013-12-31
      • 2021-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-08
      • 1970-01-01
      相关资源
      最近更新 更多