python walk歷遍目錄
阿新 • • 發佈:2017-12-27
return 其他 spec size mat cif true pos lena
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])
python walk歷遍目錄