python办公自动化之分析日志文件

实现效果:根据关键字xx搜索关键字在日志的占比

前提:把日志保存到txt文件里

代码:

python 复制代码
# 读取准备好的日志文件log_file
log_file='log_file.txt'
with open(log_file,'r') as logfile:
    text=logfile.readlines()
# 设置搜索的关键字:error
search_term='error'
# 报错的行数
error_lines=[line for line in text if search_term in line]
# 统计总行数和error行数
total_lines=len(text)
count_error=len(error_lines)
error_rate=(count_error/total_lines)*100
# 保留2位小数
rate=format(error_rate,'.2f')

print(total_lines)
print(count_error)
print(f'{rate}%')
# 把统计的结果写进日志文件
with open('log_file.txt','a') as file:
    file.write('\n'f'日志文件一共有{total_lines}行')
    file.write('\n'f'日志文件的error率是{rate}%')
file.close()

代码效果(有多行是因为我在调试中运行了多次代码)

相关推荐
寻星探路2 小时前
【深度长文】万字攻克网络原理:从 HTTP 报文解构到 HTTPS 终极加密逻辑
java·开发语言·网络·python·http·ai·https
lly2024063 小时前
Bootstrap 警告框
开发语言
2601_949146534 小时前
C语言语音通知接口接入教程:如何使用C语言直接调用语音预警API
c语言·开发语言
曹牧4 小时前
Spring Boot:如何测试Java Controller中的POST请求?
java·开发语言
KYGALYX4 小时前
服务异步通信
开发语言·后端·微服务·ruby
zmzb01034 小时前
C++课后习题训练记录Day98
开发语言·c++
ValhallaCoder4 小时前
hot100-二叉树I
数据结构·python·算法·二叉树
猫头虎5 小时前
如何排查并解决项目启动时报错Error encountered while processing: java.io.IOException: closed 的问题
java·开发语言·jvm·spring boot·python·开源·maven
YUJIANYUE5 小时前
PHP纹路验证码
开发语言·php
仟濹6 小时前
【Java基础】多态 | 打卡day2
java·开发语言