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()

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

相关推荐
闲猫16 分钟前
LangChain / Core components / Models
开发语言·python·langchain
-银雾鸢尾-2 小时前
C#中的索引器
开发语言·c#
Qlittleboy2 小时前
PHP的接口参数传递的过多,max_input_vars = 5000
开发语言·php
Aurorar0rua2 小时前
CS50 x 2024 Notes Algorithms - 02
c语言·开发语言·学习方法
en.en..2 小时前
冒泡排序与选择排序完整对比解析
开发语言·数据结构·算法·c#·排序算法
兰令水2 小时前
hot100【acm版】【2026.7.18打卡-java版本】
java·开发语言·算法
cui_ruicheng3 小时前
Python从入门到实战(十三):模块、包与环境管理
开发语言·python
就叫飞六吧3 小时前
子页面和dialog案例
开发语言·javascript·ecmascript
geovindu3 小时前
CSharp: Decorator Pattern
开发语言·后端·c#·装饰器模式·结构型模式
李宸净3 小时前
Web自动化测试selenium+python
前端·python·selenium