09/9
17:49
IT python

用python查找目录下特定后缀名的文件

上代码

import os

filte_suffix = ['.jpg','.jpeg','.png']
dirs = ['dir1/', 'dir2/', 'dir3/']

fd = open('result.txt', 'w')

def endWith(endstring):
    ends = endstring
    def run(s):
        f = map(s.endswith, ends)
        if True in f: return s
    return run


def involve_dir(arg, dirname, names):
    a = endWith(filte_suffix)
    fs = filter(a, names)
    for eachf in fs:
        tp_path = os.path.join(dirname, eachf)
        wt_path = os.path.abspath(tp_path)
        fd.write(wt_path+'\n')
        print wt_path
            
def search_dirs(dirs):
    for eachdir in dirs:
        assert(os.path.exists(eachdir))
        os.path.walk(eachdir, involve_dir, ())
    
if __name__ == '__main__':
    search_dirs(dirs)

发表评论