使用递归函数实现tree功能显示目录结构:
import os
import sys
def list_files(path):
if os.path.isdir(path):
print(path + ':')
content = os.listdir(path)
print(content)
for fname in content:
fname = os.path.join(path, fname)
list_files(fname)
if __name__ == '__main__':
list_files(sys.argv[1]) # python3 dir.py /data/weblog
结果输出:
hejianping@VM-0-2-ubuntu:~$ python dir.py /data/weblog
/data/weblog:
['nginx']
/data/weblog/nginx:
['my-sweetheart.cn.error.log', 'www.test.com.error.log', 'www.test.com.access.log', 'my-sweetheart.cn.access.log']
hejianping@VM-0-2-ubuntu:~$ tree /data/weblog/
/data/weblog/
└── nginx
├── my-sweetheart.cn.access.log
├── my-sweetheart.cn.error.log
├── www.test.com.access.log
└── www.test.com.error.log
1 directory, 4 files
hejianping@VM-0-2-ubuntu:~$
来源:https://www.cnblogs.com/hejianping/p/10969928.html