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

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

相关推荐
用户8356290780514 小时前
Python 实现 PowerPoint 形状动画设置
后端·python
ponponon5 小时前
时代的眼泪,nameko 和 eventlet 停止维护后的项目自救,升级和替代之路
python
Flittly5 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(5)Skills (技能加载)
python·agent
敏编程5 小时前
一天一个Python库:pyarrow - 大规模数据处理的利器
python
Flittly7 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(4)Subagents (子智能体)
python·agent
明月_清风14 小时前
Python 装饰器前传:如果不懂“闭包”,你只是在复刻代码
后端·python
明月_清风14 小时前
打破“死亡环联”:深挖 Python 分代回收与垃圾回收(GC)机制
后端·python
ZhengEnCi1 天前
08c. 检索算法与策略-混合检索
后端·python·算法
明月_清风2 天前
Python 内存手术刀:sys.getrefcount 与引用计数的生死时速
后端·python
明月_清风2 天前
Python 消失的内存:为什么 list=[] 是新手最容易踩的“毒苹果”?
后端·python