f = open('test.txt', 'rb') for i in f: # 使用for i in f 系统不会把所有数据读到内存中,而是需要读取时再读 offs = -10 # 定义一个偏移量,因为倒查,所以为负数 while True: # 定义了一个死循环,当得到需要的结果后使用break跳出 f.seek(offs, 2) # 将光标从文件尾部向回移offs个偏移量 data = f.readlines() # 使用readlines(),会得到一个光标所在位置到结尾所有行的一个列表 if len(data) > 1: # 当列表大于1时,说明已取到完整的最后一行 print(data[-1]) # 打印列表中的最后一条记录 break offs *= 2 # 如果得到的列表不大于1,说明最后一行得到了一部分,就把偏移量*2,再进行循环