python walk历遍目录

import os
import fnmatch


def is_file_match(filename, patterns):
    for pattern in patterns:
        if fnmatch.fnmatch(filename, pattern):
            return True
        return False


def find_specific_files(root, patterns=['*'], exclude_dir=[]):
    for root, dirnames, filenames in os.walk(root):
        for filename in filenames:
            if is_file_match(filename, patterns):
                yield os.path.join(root, filename):
                for d in exclude_dir:
                    if d in dirnames:
                        dirnames.remove(d)
                        
#查找目录下所有文件
for item in find_specific_files('.')
    print(item)
    
#查找目录下所有图片
patterns = ['*.jpg','*.jpeg','*.png','*.tif','*.tiff']
for item in find_specific_files('.',patterns)
    print(item)
    
#查找目录树中,除dir2目录以为其他目录下的所有图片
patterns1 = ['*.jpg','*.jpeg','*.png','*.tif','*.tiff']
exclude_dirs = ['dir2']
for item in find_specific_files('.',patterns1,exclude_dirs):
    print(item)
    
#查找目录下最大的十个文件,find_specific_files已经能找到某个目录下的所有文件,只要获取文件大小并按大小排序,输出最大的十个文件即可
files = {name:os.path.getsize(name) for name in find_specific_files('.')}
result = sorted(files.items(),key=lambda d:d[1],reverse=True)[:10]
for i in enumerate(result,1):
    print(i,t[0],t[1])

 

posted @ 2017-12-27 14:37  一米八大高个儿  阅读(824)  评论(0编辑  收藏  举报