温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

使用python怎么自动清理文件夹旧文件

发布时间:2021-05-10 17:06:31 来源:亿速云 阅读:142 作者:Leah 栏目:开发技术

使用python怎么自动清理文件夹旧文件?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

Python主要用来做什么

Python主要应用于:1、Web开发;2、数据科学研究;3、网络爬虫;4、嵌入式应用开发;5、游戏开发;6、桌面应用开发。

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

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

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

关于使用python怎么自动清理文件夹旧文件问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI