App下載

python實(shí)現(xiàn)自動(dòng)清理文件夾舊文件

你是我的所有夢 2021-08-21 13:43:47 瀏覽數(shù) (2281)
反饋

在日常使用中,有些文件會(huì)越積累越多,而這些文件大多已經(jīng)沒有價(jià)值了,那么怎么用python來實(shí)現(xiàn)啟動(dòng)清理這些文件夾舊文件呢?今天小編帶你了解。

本文實(shí)例為大家分享了Android九宮格圖片展示的具體代碼,供大家參考,具體內(nèi)容如下

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

采用開線程的方式,在線程里每隔一段時(shí)間鍵執(zhí)行一次監(jiān)測過程。

即  測文件夾大小->若超過則將文件夾里的文件按最后修改時(shí)間排序->刪除一些最早的圖片->刪的過程中監(jiān)測文件夾大小是否符合要求 

# -*- coding: utf-8 -*-
 
# 
# 開線程檢測文件夾大小,超過指定大小,則按文件最后修改時(shí)間排序并刪除一部分舊圖片
# 在線程里每隔一段時(shí)間檢測一次
#
 
import os
import threading
import time
 
 
#文件按最后修改時(shí)間排序
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超過后要?jiǎng)h除的大小(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])
    
 
#檢測線程,每個(gè)5秒檢測一次
def detectPicSize():
    while True:
        print('======detect============')
        detect_file_size("../pic/", 30, 5)
        time.sleep(5)
  
if __name__ == "__main__":
    #創(chuàng)建檢測線程
    detect_thread = threading.Thread(target = detectPicSize)
    detect_thread.start()

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持W3Cschool。


0 人點(diǎn)贊