python實現自動保留最近的幾個文件

# -*- 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)

發佈了61 篇原創文章 · 獲贊 26 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章