不想在python中调用shell,需要实现一个类似linux tree命令的功能
[root@python_test OcApi]# tree
.
|-- OCenter
| |-- Lib
| | |-- Mysql.php
| | `-- Think.php
| |-- Model
| | |-- Base.php
| | `-- User.php
| `-- OCenter.php
`-- oc.php
代码示例如下
#coding:utf-8
import os
def list_files(startpath):
for root, dirs, files in os.walk(startpath):
level = root.replace(startpath, '').count(os.sep)
dir_indent = "| " * (level-1) + "|-- "
file_indent = "| " * level + "|-- "
if not level:
print('.')
else:
print('{}{}'.format(dir_indent, os.path.basename(root)))
for f in files:
print('{}{}'.format(file_indent, f))
list_files('/root/OcApi')
输出结果
.
|-- oc.php
|-- OCenter
| |-- OCenter.php
| |-- Lib
| | |-- Think.php
| | |-- Mysql.php
| |-- Model
| | |-- User.php
| | |-- Base.php
os.walk() 方法为我们遍历目录树,每次进入一个目录,它会返回一个三元组,包含相对于查找目录的相对路径,一个该目录下的目录名列表,以及那个目录下面的文件名列表。