python 实现保存最新的三份文件,其余的都删掉

yipeiwu_com6年前Python基础

我就废话不多说了,直接上代码吧!

"""
对于每天存储文件,文件数量过多,占用空间
采用保存最新的三个文件
"""
from airflow import DAG
from airflow.operators.python_operator import PythonOperator
from airflow.models import Variable
from sctetl.airflow.utils import dateutils
from datetime import datetime,timedelta
import logging
import os
import shutil
"""
base_dir = "/data"
data_dir = "/gather"
"gather下边存在不同的文件夹"
"/data/gather/test"
"test路径下有以下文件夹"
"20180812、20180813、20180814、20180815、20180816"
"""
 
base_dir = Variable.get("base_dir")
data_dir = Variable.get("data_dir")
keep = 3
 
default_arg = {
  "owner":"airflow",
  "depends_on_past":False,
  "start_date":dateutils.get_start_date_local(2018,8,27,18,5),
  "email":[''],
  "email_on_failure":False,
  "email_on_retry":False,
  "retries":1,
  "retry_delay":timedelta(minutes=5)
}
 
dag = DAG(dag_id="keep_three_day",default_args=default_arg,schedule_interval=dateutils.get_schedule_interval_local(18,5))
 
def keep_three_day():
  path = os.path.join(base_dir, data_dir)
  date_cates = os.listdir(path)
  for cate in date_cates:
    p = os.path.join(base_dir, data_dir, cate)
    if os.path.isdir(p):
      dir_names = os.listdir(p)
      dir_names.sort()
      for i in dir_names[:-keep]:
        logging.info("删除目录 {path}".format(path=os.path.join(p, i)))
        shutil.rmtree(os.path.join(p, i))
 
with dag:
  keep_three_file = PythonOperator(task_id="keep_three_file",python_callable=keep_three_day(),dag=dag)
 
keep_three_file
 

以上这篇python 实现保存最新的三份文件,其余的都删掉就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python和c语言的主要区别总结

python和c语言的主要区别总结

Python可以说是目前最火的语言之一了,人工智能的兴起让Python一夜之间变得家喻户晓,Python号称目前最最简单易学的语言,现在有不少高校开始将Python作为大一新生的入门语言...

Django中url的反向查询的方法

Django中url的反向查询的方法

本文介绍了Django中url的反向查询的方法,分享给大家,具体如下: 明确几个概念: 1、application namespace : 正在部署的app的名称,一个app的多个...

详解Python的Django框架中的通用视图

详解Python的Django框架中的通用视图

通用视图 1. 前言 回想一下,在Django中view层起到的作用是相当于controller的角色,在view中实施的 动作,一般是取得请求参数,再从model中得到数据,再通过数据...

Python3.6.0+opencv3.3.0人脸检测示例

Python3.6.0+opencv3.3.0人脸检测示例

网上有很多关于Python+opencv人脸检测的例子,并大都附有源程序。但是在实际使用时依然会遇到这样或者那样的问题,在这里给出常见的两种问题及其解决方法。 先给出源代码:(如下)...

Python中fnmatch模块的使用详情

fnamtch就是filenamematch, 在python中利用符合linuxshell风格的匹配模块来进行文件名的匹配筛选工作。 fnmatch()函数匹配能力介于简单的字符串方法...