Python删除过期Log文件操作实例解析
本文详细解析如何使用Python脚本定期清理过期日志文件。通过os.walk遍历目录结构,结合os.path.getmtime获取修改时间,并制定保留策略(如保留特定后缀或近期文件)。最终通过crontab定时执行脚本,自动删除/var/server/log下超过指定天数的日志,保障服务器磁盘空间。
本文主要探讨如何利用Python脚本实现过期日志文件的自动清理,具体操作步骤如下。
1. 使用Python遍历目录结构
利用os.walk方法可以便捷地获取目录下的所有文件,该方法返回一个包含三个元素的元组(dirpath, dirnames, filenames)。其中,dirpath表示当前目录的路径;dirnames是一个列表,包含dirpath下的所有子目录名称;filenames也是一个列表,包含非目录文件。若需获取文件的完整路径,应使用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目录下的过期文件。
总结
以上即为本文关于Python删除过期log文件操作实例的完整解析,希望能对大家有所帮助。感兴趣的朋友可继续查阅本站其他相关专题,如有不足之处,欢迎留言指正。感谢各位对本站的支持!
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













