python 实时遍历日志文件
open遍历一个大日志文件
使用readlines()还是readline()?
总体上readlines()不慢于python一次次调用readline(),因为前者的循环在C语言层面,而使用readline()的循环是在Python语言层面。
但是readlines()会一次性把全部数据读到内存中,内存占用率会过高,readline()每次只读一行,对于读取大文件,需要做出取舍。
如果不需要使用seek()定位偏移,forlineinopen('file')速度更佳。
使用readlines(),适合量级较小的日志文件
importos
importtime
defcheck():
p=
whileTrue:
f=open("log.txt","r+")
f=open("result.txt","a+")
f.seek(p,)
#readlines()方法
filelist=f.readlines()
iffilelist:
forlineinfilelist:
#对行内容进行操作
f.write(line)
#获取当前位置,为下次while循环做偏移
p=f.tell()
print'nowp',p
f.close()
f.close()
time.sleep()
if__name__=='__main__':
check()
使用readline(),避免内存占用率过大
importos
importtime
defcheck():
p=
whileTrue:
f=open("log.txt","r+")
f=open("result.txt","a+")
f.seek(p,)
#whilereadline()方法
whileTrue:
l=f.readline()
#空行同样为真
ifl:
#对行内容操作
f.write(l)
else:
#获取当前位置,作为偏移值
p=f.tell()
f.close()
f.close()
break
print'nowp',p
time.sleep()
if__name__=='__main__':
check()热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下