# -*- coding:utf-8 -*-
# !/usr/bin/env python3
# name : Alenx
# 实现自动保留ctime最近的几个文件
import os
def rm_backup(rm_path, days):
files_list = os.listdir(rm_path)
list = []
dict = {}
for i in files_list:
all_path = os.path.join(rm_path, i)
ctime = os.path.getctime(all_path)
dict[all_path] = ctime
AllPathCtimeList = sorted(dict.items(), key=lambda item: item[1])
# sorted方法可按照字典的key和value进行排序,这里的key是一个lambda函数,表示按照选取元组dict.items()中的第二个元素进行排序
if len(AllPathCtimeList) <= days:
pass
else:
for i in range(len(AllPathCtimeList) - days):
os.remove(AllPathCtimeList[i][0])
# '''AllPathCtimeList[i][0]'''取AllPathCtimeList中的第i的元素,然后取第i个元素中的第0个元素
rm_paths = ('D:/test/test1', 'D:/test/test2')
for rm in rm_paths:
rm_backup(rm, 3)
python实现自动保留最近的几个文件
最新推荐文章于 2021-10-20 11:51:59 发布