思路比较简单,使用os.walk 生成目录信息,然后再进行字符串操作,所以没有其他比较复杂的逻辑,但是生成的效果也比较简单,自己看看到是可以哈。
代码如下
# -*- coding: utf-8 -*-
'''
Created on July 22, 2017
@author: hehe1234567
'''
import os
def simple_dir_tree(ddir):
for dirpath,dirnames,filenames in os.walk(ddir.strip(os.sep)):
if dirpath == ddir:
string = ''
for f in filenames:
string = string + '\n' + ' '*len(dirpath) + '|__' + str(f)
print ddir +string
else:
dirn = os.path.basename(dirpath)
string = ' '*len(os.path.dirname(dirpath)) + '|__' + dirn
for f in filenames:
string = string + '\n' + ' '*len(dirpath) + '|__' + str(f)
print string
if __name__ == '__main__':
simple_dir_tree('C:\\Users\\Auser.MEY\\Desktop\\loadbalance-playbook\\loadbalance-playbook')
生成的目录树如下: