网络编程
位置:首页>> 网络编程>> Python编程>> python删除过期log文件操作实例解析

python删除过期log文件操作实例解析

作者:y2701310012  发布时间:2021-02-03 18:29:36 

标签:python,log文件

本文研究的主要是python删除过期log文件的相关内容,具体介绍如下。

1. 用Python遍历目录

os.walk方法可以很方便的得到目录下的所有文件,会返回一个三元的tupple(dirpath, dirnames, filenames),其中,dirpath是代表目录的路径,dirnames是一个list,包含了dirpath下的所有子目录的名字,filenames是一个list,包含了非目录的文件,如果需要得到全路径,需要使用os.path.join(dirpath,name).例如test目录的结构为:

test------------file_c
|
-----------dir_a1/file_a1
| |
| -------dir_a2/file_a2
|
------------dir_b1/file_b1

那么使用如下代码:


import os

for i in os.walk('test'):
  print i

结果为:

('test', ['dir_a1', 'dir_b1'], ['file_c1'])('test/dir_a1', ['dir_a2'], ['file_a1'])('test/dir_a1/dir_a2', [], ['file_a2'])('test/dir_b1', [], ['file_b1'])

要得到带路径的文件,则可以这样操作:


for i in os.walk('test'):
  #print i
  for j in i[2]:
    os.path.join(i[0],j)

结果为:

'test/file_c1'
'test/dir_a1/file_a1'
'test/dir_a1/dir_a2/file_a2'
'test/dir_b1/file_b1'

当然,也可以利用os.path.isdir判断来递归操作得到目录中的文件:


def walk(dir):
 ret = []
 dir = os.path.abspath(dir)
 for file in [file for file in os.listdir(dir) if not file in [".",".."]]:
   nfile = os.path.join(dir,file)
   if os.path.isdir(nfile):
     ret.extend( walk(nfile) )
   else:
     ret.append( nfile )
 return ret

2. 排除需要保留文件

根据特定名称的文件以及文件更改时间来判断是否需要删除,os.path.getmtime(file)来得到文件最后改变的时间,当然除了诸如“XXX" in file的方法来判断文件名外,也可以采用正则表达式的方法。


def shouldkeep(file):
 if '.py' in file:
   return True
 elif '.conf' in file:
   return True
 elif 'current' in file:
   return True
 elif 'rtb' in file and datetime.datetime.fromtimestamp( os.path.getmtime(file) ) > datetime.datetime.now() - datetime.timedelta(3):
   return True
 # the log webdebug/popterr/webaccess/controller_slow/game/checking_social which are modified 6 day ago should be removed
 elif datetime.datetime.fromtimestamp( os.path.getmtime(file) ) < \
    datetime.datetime.now() - datetime.timedelta(6)\
    and ('webdebug' in file \
    or 'potperr' in file\
    or 'webaccess' in file\
    or 'controller_slow' in file\
    or 'game.' in file\
    or 'checkin_social' in file\
    ):
   return False
 elif datetime.datetime.fromtimestamp( os.path.getmtime(file) ) < \
    datetime.datetime.now() - datetime.timedelta(2)\
    and ('queue.master.info' in file):
   return False
 elif datetime.datetime.fromtimestamp( os.path.getmtime(file) ) > \
    datetime.datetime.now() - datetime.timedelta(6):
   return True
 else:
   return False

files = walk('/var/server/log')
for i in files:
 if not shouldkeep(i):
   print i, datetime.datetime.fromtimestamp( os.path.getmtime(i) )
   os.remove( i )

将该脚本用crontab定时每天执行一次,即可定期每天清理/var/server/log下的过期文件。

来源:http://blog.csdn.net/y2701310012/article/details/41783045

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com