open 遍历一个大日志文件
使用 readlines() 还是 readline() "htmlcode">
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()