python脚本实现自动保留ctime最近的几个文件

使用了给字典排序的sorted方法

 1 #!/usr/bin/env python
 2 # coding:utf-8
 3 import os
 4 def rm_backup(rm_path,days):
 5     files_list = os.listdir(rm_path)
 6     list = []
 7     dict = {}
 8     for i in files_list:
 9         all_path = os.path.join(rm_path,i)
10         ctime = os.path.getctime(all_path)    
11         dict[all_path] = ctime
12     #print dict.items()
13     AllPathCtimeList = sorted(dict.items(),key=lambda item:item[1])
14     #sorted方法可按照字典的key和value进行排序,这里的key是一个lambda函数,表示按照选取元组dict.items()中的第二个元素进行排序
15     if len(AllPathCtimeList) <= days:
16         pass
17     else :
18         for i in range(len(AllPathCtimeList)-days):
19             os.remove(AllPathCtimeList[i][0])
20             #'''AllPathCtimeList[i][0]'''取AllPathCtimeList中的第i的元素,然后取第i个元素中的第0个元素
21 
22 rm_paths = ('D:/test/test1','D:/test/test2')            
23 for rm in rm_paths:
24     
25         rm_backup(rm, 3)

 

posted @ 2016-11-08 09:07  Dylan_Wu  阅读(723)  评论(0编辑  收藏  举报