在进行Python项目开发(http://www.maiziedu.com/course/python/)中我们需要遍历一个大日志文件,在这个时候我们应该使用readlines()还是readline()?虽然这两个方法都是读取数据,可是读取的方法不同,readlines() 会一次性把全部数据读到内存中,内存占用率会过高,readline() 每次只读一行,对于读取大文件, 需要做出取舍。下面就通过案例来讲解readline()和readlines()。
如果不需要使用 seek() 定位偏移, for line in open('file') 速度更佳。
使用 readlines() ,适合量级较小的日志文件
import os
import time
def check():
p = 0
while True:
f = open("log.txt", "r+")
f1 = open("result.txt", "a+")
f.seek(p, 0)
#readlines()方法
filelist = f.readlines()
if filelist:
for line in filelist:
#对行内容进行操作
f1.write(line)
#获取当前位置,为下次while循环做偏移
p = f.tell()
print 'now p ', p
f.close()
f1.close()
time.sleep(2)
if __name__ == '__main__':
check()
使用 readline(),避免内存占用率过大
import os
import time
def check():
p = 0
while True:
f = open("log.txt", "r+")
f1 = open("result.txt", "a+")
f.seek(p, 0)
#while readline()方法
while True:
l = f.readline()
#空行同样为真
if l:
#对行内容操作
f1.write(l)
else:
#获取当前位置,作为偏移值
p = f.tell()
f.close()
f1.close()
break
print 'now p', p
time.sleep(2)
if __name__ == '__main__':
check()
以上就是全部内容,在进行Python项目开发时,我们要根据自己的需求,权衡利弊来选择方法使用,这样也能减少后期损失等问题,通过上面的案例讲解,已经充分了解readline()和readlines()的使用方法了吧,如果还不是很熟悉,那就需要多去实践操作了。