现在的位置: 首页 > 综合 > 正文

python 遍历目录

2013年10月11日 ⁄ 综合 ⁄ 共 296字 ⁄ 字号 评论关闭

树形列出一个目录的递归结构,在linux下有点像tree这个命令。

在windows下运行:

from os.path import basename, isdir
from os import listdir

def traverse(path, depth=0):
    print depth* '|' + '--', basename(path)
    if(isdir(path)):
        for item in listdir(path):
            traverse(path+'\\'+item, depth+1)

if __name__ == '__main__':
    traverse('c:\\Program Files')

注:这里有个重点就是自定义函数的自调用

抱歉!评论已关闭.