Python查找目录下最大及最近的文件

注:部分内容来自书籍或者网络,如有侵权,请联系删除。

#!/usr/bin/python
# -*- coding:UTF-8 -*-
from __future__ import print_function
import os
import time
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(path,patterns=['*'],exclude_dirs=[]):
    for dirpath,dirnames,filenames in os.walk(path):
        for filename in filenames:
            if is_file_match(filename,patterns):
                yield os.path.join(dirpath,filename)
        for d in exclude_dirs:
            if d in dirnames:
                dirnames.remove(d)

size_files = {name: os.path.getsize(name) for name in find_specific_files('.')}
time_files = {name: os.path.getmtime(name) for name in find_specific_files('.')}
size_result = sorted(size_files.items(),key=lambda d: d[1],reverse=True)[:10]
time_result = sorted(time_files.items(),key=lambda d: d[1],reverse=True)[:10]
for i,t in enumerate(size_result,1):
    print(i,t[0],t[1])
for i,t in enumerate(time_result,1):
    print(i,t[0],time.ctime(t[1]))


「 文章如果对你有帮助,请点个赞哦^^ 」 

0