python遍历目录

#!/usr/bin/env python
# coding:UTF-8
import os
filepath = '/data'
def fun(rootdir):
    for dirfiles in sorted(os.listdir(rootdir)):
        path_dirfiles = os.path.join(rootdir, dirfiles)
        if os.path.isdir(path_dirfiles):
            print '\033[34;1m%s\033[0m' % path_dirfiles
            fun(path_dirfiles)  #递规调用fun()
        else:
            print path_dirfiles
if __name__ == '__main__':
    fun(filepath)


代码演示:

]# python path_file.py
/data/qjp
/data/qjp/bin
/data/qjp/bin/nginx
/data/qjp/conf
/data/qjp/conf/nginx.conf
/data/qjp/log
/data/qjp/run
/data/qjp/webroot


你可能感兴趣的:(python,遍历,目录)