开发文档中需展现树状目录图,整理相关代码如下,方便后续查看学习。
from pathlib import Path
p = Path('D:\predict')
def generate_tree(pathname, n=0):
global tree_str
if pathname.is_file():
tree_str += ' |' * n + '-' * 2 + pathname.name + '\n'
elif pathname.is_dir():
tree_str += ' |' * n + '-' * 2 + \
str(pathname.relative_to(pathname.parent)) + '\n'
for cp in pathname.iterdir():
generate_tree(cp, n + 1)
if __name__ == '__main__':
generate_tree(p)