This piece of code is reading a large file line by line, process each line then end the process whenever there is no new entry:
file = open(logFile.txt', 'r')
count = 0
while 1:
where = file.tell()
line = file.readline()
if not line:
count = count + 1
if count >= 10:
break
time.sleep(1)
file.seek(where)
else:
#process line
In my experence, reading line by line takes very long time, so I tried to improve this code to read chunk of lines each time:
from itertools import islice
N = 100000
with open('logFile.txt', 'r') as file:
while True:
where = file.tell()
next_n_lines = list(islice(file, N)).__iter__()
if not next_n_lines:
count = count + 1
if count >= 10:
break
time.sleep(1)
file.seek(where)
for line in next_n_lines:
# process next_n_lines
This works fine except for the ending part, it doen't end the process (break the while loop) even if there is no more lines in file. Any suggestions?
See Question&Answers more detail:os