登录  /  注册

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

php中文网
发布: 2016-06-16 08:44:34
原创
1208人浏览过

脚本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)   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)

智能AI问答
PHP中文网智能助手能迅速回答你的编程问题,提供实时的代码和解决方案,帮助你解决各种难题。不仅如此,它还能提供编程资源和学习指导,帮助你快速提升编程技能。无论你是初学者还是专业人士,AI智能助手都能成为你的可靠助手,助力你在编程领域取得更大的成就。
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号