将指定目录生成目录树。
代码:
import os
def list_file(start_path):
for root, subdirs, files in os.walk(start_path):
# root.subdirs,files分别是父路径,子目录列表,子文件列表
level = root.replace(start_path, '').count(os.sep)
dir_indent = '| ' * level + '|--'
file_indent = '| ' * (level + 1) + '|--'
if level:
print('{}{}'.format(dir_indent, os.path.basename(root)))
else:
print('{}'.format(start_path[0]))
print('{}{}'.format('|--', start_path[3:]))
for f in files:
print('{}{}'.format(file_indent, f))
start_path = r'C:\Users\XJQ\Music\aa'
list_file(start_path)
运行结果:
C
|--Users\XJQ\Music\aa
| |--新建 DOCX 文档.docx
| |--新建 PPT 演示文稿.ppt
| |--新建 RTF 文档.rtf
| |--cc
| | |--001.txt
| | |--新建文本文档.txt
| |--新建文件夹
| | |--cc
| | | |--001.txt
| |--新建文件夹 (2)
| | |--cc
| | | |--001.txt
| | |--新建文件夹