python遍历文件每一行_python 实时遍历日志文件

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值