脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python实现自动清理文件夹旧文件

python实现自动清理文件夹旧文件

2021-10-27 09:28zebra_zzh Python

这篇文章主要为大家详细介绍了python实现自动清理文件夹旧文件,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了Android九宫格图片展示的具体代码,供大家参考,具体内容如下

由于程序一直在不停地存图,因此需要监测图片文件夹的大小,一旦超过指定大小则删除一部分最早的图片。

采用开线程的方式,在线程里每隔一段时间键执行一次监测过程。

即  测文件夹大小->若超过则将文件夹里的文件按最后修改时间排序->删除一些最早的图片->删的过程中监测文件夹大小是否符合要求 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# -*- 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()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/qq_24282081/article/details/105267969

延伸 · 阅读

精彩推荐