python 实时遍历日志文件
程序员文章站
2022-04-06 21:10:17
...
open 遍历一个大日志文件
使用 readlines() 还是 readline() ?
总体上 readlines() 不慢于python 一次次调用 readline(),因为前者的循环在C语言层面,而使用readline() 的循环是在Python语言层面。
但是 readlines() 会一次性把全部数据读到内存中,内存占用率会过高,readline() 每次只读一行,对于读取 大文件, 需要做出取舍。
如果不需要使用 seek() 定位偏移, for line in open('file') 速度更佳。
使用 readlines(),适合量级较小的日志文件
import os import time def check(): p = while True: f = open("log.txt", "r+") f = open("result.txt", "a+") f.seek(p, ) #readlines()方法 filelist = f.readlines() if filelist: for line in filelist: #对行内容进行操作 f.write(line) #获取当前位置,为下次while循环做偏移 p = f.tell() print 'now p ', p f.close() f.close() time.sleep() if __name__ == '__main__': check()
使用 readline(),避免内存占用率过大
import os import time def check(): p = while True: f = open("log.txt", "r+") f = open("result.txt", "a+") f.seek(p, ) #while readline()方法 while True: l = f.readline() #空行同样为真 if l: #对行内容操作 f.write(l) else: #获取当前位置,作为偏移值 p = f.tell() f.close() f.close() break print 'now p', p time.sleep() if __name__ == '__main__': check()
声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
相关文章
相关视频
专题推荐
-
独孤九贱-php全栈开发教程
全栈 170W+
主讲:Peter-Zhu 轻松幽默、简短易学,非常适合PHP学习入门
-
玉女心经-web前端开发教程
入门 80W+
主讲:灭绝师太 由浅入深、明快简洁,非常适合前端学习入门
-
天龙八部-实战开发教程
实战 120W+
主讲:西门大官人 思路清晰、严谨规范,适合有一定web编程基础学习
网友评论
文明上网理性发言,请遵守 新闻评论服务协议
我要评论