import osimport 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])
原文地址:https://www.cnblogs.com/qinghe123/p/8125628.html
时间: 2024-10-20 16:01:40