python 自動清理文件夾舊文件

由於程序一直在不停地存圖,因此需要監測圖片文件夾的大小,一旦超過指定大小則刪除一部分最早的圖片。

採用開線程的方式,在線程裏每隔一段時間鍵執行一次監測過程。

即  測文件夾大小->若超過則將文件夾裏的文件按最後修改時間排序->刪除一些最早的圖片->刪的過程中監測文件夾大小是否符合要求

 

# -*- coding: utf-8 -*-

# 
# 開線程檢測文件夾大小,超過指定大小,則按文件最後修改時間排序並刪除一部分舊圖片
# 在線程裏每隔一段時間檢測一次
#

import os
import threading
import time


#文件按最後修改時間排序
def get_file_list(file_path):
  dir_list = os.listdir(file_path)
  if not dir_list:
    return
  else:
    dir_list = sorted(dir_list, key=lambda x: os.path.getmtime(os.path.join(file_path, x)))
    #print(dir_list)
    return dir_list

#獲取文件夾大小
def get_size(file_path):
    totalsize=0
    for filename in os.listdir(file_path):
        totalsize=totalsize+os.path.getsize(os.path.join(file_path, filename))
    #print(totalsize / 1024 / 1024)
    return totalsize / 1024 / 1024

# 1文件目錄   2文件夾最大大小(M)   3超過後要刪除的大小(M)
def detect_file_size(file_path, size_Max, size_Del):
    print(get_size(file_path))
    if get_size(file_path) > size_Max:
        fileList = get_file_list(file_path)
        for i in range(len(fileList)):
            if get_size(file_path) > (size_Max - size_Del):
                print ("del :%d %s" % (i + 1, fileList[i]))
                os.remove(file_path + fileList[i])
    

#檢測線程,每個5秒檢測一次
def detectPicSize():
    while True:
        print('======detect============')
        detect_file_size("../pic/", 30, 5)
        time.sleep(5)
  
if __name__ == "__main__":
    #創建檢測線程
    detect_thread = threading.Thread(target = detectPicSize)
    detect_thread.start()
    

    
            

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章