【问题标题】:How to generate a Python directory list (tree structure)?如何生成 Python 目录列表(树形结构)?
【发布时间】:2021-02-17 06:58:06
【问题描述】:

我知道我们可以使用os.walk() 列出所有子目录或目录中的所有文件。如何生成如下的树形结构,而不仅仅是列出所有目录?在某些子目录中我有数百个文件,那么如何只显示子目录中的几个文件而不列出所有文件?

doc/
├── _static/
│   ├── embedded/
│   │   ├── deep_file
│   │   └── very/
│   │       └── deep/
│   │           └── folder/
│   │               └── very_deep_file1
|   |               └── very_deep_file2
|   |               └── ......
│   └── less_deep_file
├── about.rst
├── conf.py
└── index.rst

【问题讨论】:

  • 你在打印时打破循环

标签: python file directory directory-tree


【解决方案1】:

以下内容可能会对您有所帮助:

for directory, _, filenames in os.walk('your path'):
    for filename in filenames:
        print(os.path.join(directory, filename))

【讨论】:

  • 谢谢,但它只是列出了所有目录。我有兴趣生成上面的树结构。
【解决方案2】:

os.walk 在您迭代时会为您提供root, directories, files。为什么不简单地循环 files[:5],然后在长度超过 5 时打印一个额外的 ...

【讨论】:

    猜你喜欢
    • 2019-04-23
    • 2012-04-01
    • 2014-02-02
    • 2021-12-20
    • 1970-01-01
    • 1970-01-01
    • 2012-06-13
    • 2017-04-28
    相关资源
    最近更新 更多