Python删除指定目录下过期文件的2个脚本分享


Posted in Python onApril 10, 2014

脚本1:

这两天用python写了一个删除指定目录下过期时间的脚本。也可能是我初学python,对python还不够熟习,总觉得这个脚本用shell写应该更简单也更容易些。
就功能上来说,该脚本已经实现了我想要的效果,不过该脚本还不够通用性,还有更多可以完善的地方。目前该脚本在python2.4下运行良好。同时,我在脚本中加入了对python版本的判断,理论上2.7下也应该可以正常使用。有环境的朋友可以帮忙测试一下。
该脚本不完善的地方在于,只能支持一级目录下的文件删除,还不支持目录递归。同时过期文件的定义只能按week来做。

Python代码:

#! /usr/bin/env python
# -*- coding=utf-8 -*-
import sys
import os
import time,datetime# 定义需要删除文件的目录
dir = '/data/webbak/'
# 被删除文件写入日志文件
logdir = '/var/log'
logfile = os.path.join(logdir, 'delete.log')
# 获取当前系统python版本
ver = sys.version
ver = ver.split(' ')
ver = ver[0]
# 将"Wed Jul  4 13:25:59 2012"格式的时间转成“2012-07-02 14:50:15”格式的时间
# version是当前系统python版本号
# time是"Wed Jul  4 13:25:59 2012"格式的时间
# 函数返回"2012-07-02 14:50:15"格式的时间
def string2time(str_time, version = ver):
 version_l = version.split('.')[0:2]
 ver = version_l[0] + '.' + version_l[1] 
 if (ver == '2.7'):
  f_time = datetime.datetime.strptime(str_time, time_format)
  f_time = f_time.strftime('%Y-%m-%d %H:%M:%S')
  return f_time
 elif(ver == '2.4'):
  f_time = time.strptime(str_time, time_format)
  f_time = datetime.datetime(*f_time[0:6])
  return f_time
# 时间格式
time_format = "%a %b %d %H:%M:%S %Y"
# 取得当前时间
today = datetime.datetime.now()
# 定义4个星期
four_weeks = datetime.timedelta(weeks=6)
# 4星期前的日期
four_weeks_ago = today - four_weeks
# 将时间转成timestamps
four_weeks_ago_timestamps = time.mktime(four_weeks_ago.timetuple())
# 列出目录中的所有文件
files = os.listdir(dir)
# 打开要删除的文件日志
fh = open(logfile, "w+")
# 遍历文件,打印出文件的创建时间
for f in files:
 # 忽略掉.开头的文件
 if f.startswith('.'):
  continue
 # 忽略掉当前目录下的目录
 if os.path.isdir(os.path.join(dir,f)):
  continue
 # 获得文件的modify时间,并转换成timestamp格式
 file_timestamp = os.path.getmtime(os.path.join(dir, f))
 file_time_f = string2time(time.ctime(file_timestamp))
 if float(file_timestamp) <= float(four_weeks_ago_timestamps):
  fh.write(str(today) + "\t" + str(file_time_f) + "\t" + os.path.join(dir,f) + "\n")
  os.remove(os.path.join(dir,f))
# 关闭文件
fh.close()

脚本2:
实现类似下面的Shell命令的操作

find  /data/log -ctime +5 | xargs  rm  -f

Python代码:
import os
import sys
import time
class DeleteLog:

    def __init__(self,fileName,days):
        self.fileName = fileName
        self.days = days
    def delete(self):
        if os.path.isfile(self.fileName):
            fd = open(self.fileName,'r')
            while 1:
                buffer = fd.readline()
                if not buffer : break
                if os.path.isfile(buffer):
                    os.remove(buffer)
            fd.close()
        elif os.path.isdir(self.fileName):
            for i in [os.sep.join([self.fileName,v]) for v in os.listdir(self.fileName)]:
                print i
                if os.path.isfile(i):
                    if self.compare_file_time(i):
                        os.remove(i)
                elif os.path.isdir(i):
                    self.fileName = i
                    self.delete()
    def compare_file_time(self,file):
        time_of_last_access = os.path.getatime(file)
        age_in_days = (time.time()-time_of_last_access)/(60*60*24)
        if age_in_days > self.days:
            return True
        return False
if __name__ == '__main__':
    if len(sys.argv) == 2:
        obj = DeleteLog(sys.argv[1],0)
        obj.delete()
    elif len(sys.argv) == 3:
        obj = DeleteLog(sys.argv[1],int(sys.argv[2]))
        obj.delete()
    else:
        print "usage: python %s listFileName|dirName [days]" % sys.argv[0]
        sys.exit(1)
Python 相关文章推荐
Python编写的com组件发生R6034错误的原因与解决办法
Apr 01 Python
Python采集腾讯新闻实例
Jul 10 Python
跟老齐学Python之玩转字符串(3)
Sep 14 Python
Python装饰器的函数式编程详解
Feb 27 Python
实例讲解Python中SocketServer模块处理网络请求的用法
Jun 28 Python
python:socket传输大文件示例
Jan 18 Python
python实现简易云音乐播放器
Jan 04 Python
Python英文文本分词(无空格)模块wordninja的使用实例
Feb 20 Python
详解Ubuntu16.04安装Python3.7及其pip3并切换为默认版本
Feb 25 Python
python安装pil库方法及代码
Jun 25 Python
浅谈Pycharm最有必要改的几个默认设置项
Feb 14 Python
OpenCV3.3+Python3.6实现图片高斯模糊
May 18 Python
python实现随机密码字典生成器示例
Apr 09 #Python
Python下的Mysql模块MySQLdb安装详解
Apr 09 #Python
使用python实现递归版汉诺塔示例(汉诺塔递归算法)
Apr 08 #Python
python计算圆周长、面积、球体体积并画出圆
Apr 08 #Python
python实现类似ftp传输文件的网络程序示例
Apr 08 #Python
Python collections模块实例讲解
Apr 07 #Python
python操作xml文件示例
Apr 07 #Python
You might like
php 自写函数代码 获取关键字 去超链接
2010/02/08 PHP
php中记录用户访问过的产品,在cookie记录产品id,id取得产品信息
2011/05/04 PHP
YII Framework框架教程之安全方案详解
2016/03/14 PHP
PHP正则删除HTML代码中宽高样式的方法
2017/06/12 PHP
PDO::lastInsertId讲解
2019/01/29 PHP
PHP实现简易图形计算器
2020/08/28 PHP
实例详解angularjs和ajax的结合使用
2015/10/22 Javascript
js实现浏览器倒计时跳转页面效果
2016/08/12 Javascript
值得分享的Bootstrap Table使用教程
2016/11/23 Javascript
js图片延迟加载(Lazyload)三种实现方式
2017/03/01 Javascript
NodeJS测试框架mocha入门教程
2017/03/28 NodeJs
vue中echarts3.0自适应的方法
2018/02/26 Javascript
浅析微信扫码登录原理(小结)
2018/10/29 Javascript
node+express框架中连接使用mysql(经验总结)
2018/11/10 Javascript
详解vue 兼容IE报错解决方案
2018/12/29 Javascript
vue实现移动端省市区选择
2019/09/27 Javascript
jQuery实现本地存储
2020/12/22 jQuery
[01:38]DOTA2辉夜杯 欢乐的观众现场采访
2015/12/26 DOTA
Python实现全角半角转换的方法
2014/08/18 Python
python在windows下实现ping操作并接收返回信息的方法
2015/03/20 Python
仅用50行Python代码实现一个简单的代理服务器
2015/04/08 Python
python实现批量按比例缩放图片效果
2018/03/30 Python
python绘制中国大陆人口热力图
2018/11/07 Python
Python使用ffmpy将amr格式的音频转化为mp3格式的例子
2019/08/08 Python
用Python解数独的方法示例
2019/10/24 Python
python 负数取模运算实例
2020/06/03 Python
Python基于Faker假数据构造库
2020/11/30 Python
表达自我的市场:Society6
2018/08/01 全球购物
总经理任命书
2014/03/29 职场文书
2014年五四青年节演讲比赛方案
2014/04/22 职场文书
学生党员公开承诺书
2014/05/28 职场文书
学习三严三实对照检查材料思想汇报
2014/09/22 职场文书
2015年党员干部承诺书
2015/01/21 职场文书
2016年情人节广告语
2016/01/28 职场文书
如何在Python中妥善使用进度条详解
2022/04/05 Python
python自动获取微信公众号最新文章的实现代码
2022/07/15 Python