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

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

相关推荐
aqi001 小时前
15天学会AI应用开发(八)使用向量数据库实现RAG功能
人工智能·python·大模型·ai编程·ai应用
Csvn2 小时前
`functools.lru_cache` —— 一行代码搞定缓存加速
后端·python
金銀銅鐵19 小时前
[Python] 从《千字文》中随机挑选汉字
后端·python
cup111 天前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi001 天前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵1 天前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf1 天前
Agent 流程编排
后端·python·agent
copyer_xyf1 天前
Agent RAG
后端·python·agent