Python ---- 找出'/mnt'目录下最大(最早)的十个文件

 今天看了一下Python自动化的书,里边儿有个这个需求,尝试做了一下,感觉还凑合= =,记录一下我的Python自动化学习过程;

先定义一个通用函数,可被循环;(其实上一篇博客里就有)

#!/usr/bin/python3

import os, 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_dirs=[]):
      for root,dirnames,filenames in os.walk(root):
           for filename in filenames:
                if is_file_match(filename, patterns):
                   yield os.path.join()
           for d in exclude_dirs:
               if d in dirnames:
                  dirname.remove(d)

就可以使用ipython啦或者再写一个文件来解决:

import file,os

def big_file():
    big = {}
    for name in file.find_specific_files('/mnt'):
        big[name] = os.path.getsize(name)
    big = sorted(big.items(),key=lambda x:x[1],reverse=True)[:10]

    for i, t in enumerate(big, 1):
        print(i, t[0], t[1])

def old_file():
    old = {}
    for name in file.find_specific_files('/mnt'):
        old[name] = os.path.getmtime(name)
    old = sorted(old.items(),key=lambda x:x[1],reverse=True)[:10]
    for i, t in enumerate(old, 1):
        print(i, t[0], t[1])
big_file()
old_file()

 

以下是运行结果

 

posted @ 2020-05-13 17:44  k-free  阅读(446)  评论(0编辑  收藏  举报