python 实时遍历日志文件

WBOY
풀어 주다: 2016-06-10 15:05:16
원래의
1363명이 탐색했습니다.

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()
로그인 후 복사

원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!