几天前我遇到了这个问题,我使用了这个解决方案。我的解决方案类似于@Frerich Raabe 的解决方案,但没有随机性,只是逻辑:)
def get_last_line(f):
""" f is a file object in read mode, I just extract the algorithm from a bigger function """
tries = 0
offs = -512
while tries < 5:
# Put the cursor at n*512nth character before the end.
# If we reach the max fsize, it puts the cursor at the beginning (fsize * -1 means move the cursor of -fsize from the end)
f.seek(max(fsize * -1, offs), 2)
lines = f.readlines()
if len(lines) > 1: # If there's more than 1 lines found, then we have the last complete line
return lines[-1] # Returns the last complete line
offs *= 2
tries += 1
raise ValueError("No end line found, after 5 tries (Your file may has only 1 line or the last line is longer than %s characters)" % offs)
tries
如果文件也有一行(最后一行非常长),则计数器避免被阻塞。该算法尝试从最后 512 个字符中获取最后一行,然后是 1024、2048 ......如果在th
迭代中仍然没有完整的行,则停止。