在python中列出目录树结构? [英] List directory tree structure in python?
本文介绍了在python中列出目录树结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道我们可以使用 os.walk()
列出目录中的所有子目录或所有文件。但是,我想列出完整的目录树内容:
I know that we can use os.walk()
to list all sub-directories or all files in a directory. However, I would like to list the full directory tree content:
- Subdirectory 1:
- file11
- file12
- Sub-sub-directory 11:
- file111
- file112
- Subdirectory 2:
- file21
- sub-sub-directory 21
- sub-sub-directory 22
- sub-sub-sub-directory 221
- file 2211
如何在Python中最好地实现此目标?
How to best achieve this in Python?
推荐答案
这是一个函数格式如下:
Here's a function to do that with formatting:
import os
def list_files(startpath):
for root, dirs, files in os.walk(startpath):
level = root.replace(startpath, '').count(os.sep)
indent = ' ' * 4 * (level)
print('{}{}/'.format(indent, os.path.basename(root)))
subindent = ' ' * 4 * (level + 1)
for f in files:
print('{}{}'.format(subindent, f))
这篇关于在python中列出目录树结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文