Python3 development automatically cleans up old files

1. Demand background

由于服务器存储资源有限,在经过长时间的存储数据后,常会出现硬盘占满,数据写入不进去,系统、服务均会出现异常。而很多数据不必要永久存储,超过一定失效后,即可删除清理,为新数据腾出空间。
网上找到的一些辅助清理工具要么收费,要么功能太简单,不能达到项目要求。

2. Implementation method

Considering the versatility, choose python3 to implement, it can be cross-platform, Windows and Linux servers can be used

3. Configuration file style config.json

The json array format is flexible and convenient. You can set the directory to be cleaned up, and the number of days that the files in this directory need to be kept. If it exceeds, it will be automatically deleted; multiple different tasks can be formulated according to needs.

[
    {
    
    
        "dir":"D:\\Debug\\pic",
        "days":365
    }, 
    {
    
    
        "dir":"D:\\Debug\\tmp_pic",
        "days":100
    }, 
    {
    
    
        "dir":"D:\\Debug\\tmp_video",
        "days":100
    }    
]

4. Python3 implementation

#!/usr/bin/python3
#coding=utf-8
import os, datetime,time, json

#判断目录是否为空
def dir_empty(dir_path):
    return not next(os.scandir(dir_path), None)

#删除指定文件夹下的旧文件
#_dir  指定目录
#_days 保留天数
def clear_old_files(_dir,_days):
    if(not os.path.exists(_dir)):
        print(F'''路径:{
      
      _dir},不存在,请检查配置文件!''')
        return
    else:
        print(F'''开始清理:{
      
      _dir}!''')
    ds = list(os.walk(_dir)) #获得所有文件夹的信息列表
    delta = datetime.timedelta(days=_days) #设定_days天前的文件为过期
    now = datetime.datetime.now() #获取当前时间
    for d in ds: #遍历该列表
        if(dir_empty(d[0])): #空目录,删除目录           
            print('删除空目录:')
            os.rmdir(d[0])
        else:
            print(F'''进入目录:{
      
      d[0]}''')
            os.chdir(d[0]) #进入本级路径,防止找不到文件而报错
            if d[2] != []: #如果该路径下有文件
                for x in d[2]: #遍历这些文件
                    #print(F'''检查文件:{x}''')
                    ctime = datetime.datetime.fromtimestamp(os.path.getctime(x)) #获取文件创建时间
                    #print(F'''创建日期:{ctime}''')
                    if ctime < (now-delta): #若创建于delta天前
                        os.remove(x) #则删掉
                        print(F'''文件已经过期:{
      
      x},删除!''')
                    else:
                        print(F'''文件尚未过期:{
      
      x},保留!''')
            else:
                print(F'''{
      
      d[0]}, 路径下没有文件!''')
        print(F'''路径:{
      
      d[0]},检查完毕!''')
        
#自我测试    
if __name__ == "__main__":    
    print(F'''读取配置文件:''')
    with open(os.path.join(os.getcwd(), 'config.json')) as f:
        configs=json.load(f)
    print(F'''遍历配置,清理文件:''')
    while True:
        for config in configs:
            print(F'''目录:{
      
      config['dir']},保留{
      
      config['days']}天''')
            try:
                clear_old_files(config['dir'], config['days'])
            except BaseException as e:
                print(e)
        time.sleep(5)

Guess you like

Origin blog.csdn.net/lzl640/article/details/128716754