python 遍历目录树

2017-01-14  本文已影响0人  家琦的三亩地
import os,fnmatch

#root 目录,pattens 后缀名, yield_floders 是否输出文件夹, single_level是否只输出一个层次 
def all_files(root, pattens = '*', single_level = False, yield_floders = False ):
    pattens = pattens.split(';')
    for path, subdirs, files in os.walk(root):
        if yield_floders:
            files.extend(subdirs)
        files.sort()
        for name in files:
            for patten in pattens:
                if fnmatch.fnmatch(name,patten):
                    yield os.path.join(path,name)
                    break
        if single_level:
            break
#tests = all_files(r'D:\py_project',yield_floders = True, single_level = False)
#for i in tests:
    #print (i)
上一篇下一篇

猜你喜欢

热点阅读