获取光标tell、移动光标seek

f = open('data', 'r', encoding='utf-8')
print(f.tell())
print(f.readline())
print(f.tell())
print(f.readline())

seek默认相对于开始位置

f = open('data', 'r', encoding='utf-8')
f.seek(3)
print(f.read())

seek(num, 1)相对于上次的光标位置,需要用二进制进行操作

f = open('data', 'rb')
f.seek(6)
print(f.tell()) # 6
f.seek(3, 1)
print(f.tell()) # 9

seek(num, 2)从文件末尾开始读

f = open('data', 'rb')
f.seek(-3, 2)
print(f.read())

使用seek读取文件的最后一行,思路读取最后两行,再取最后一行

f = open('data', 'rb')
offs = -10
while 1:
    f.seek(offs, 2)
    data = f.readlines()
    if len(data) > 1:
        print(data[1].decode())
        break
    offs*=2

猜你喜欢

转载自blog.csdn.net/bus_lupe/article/details/84454201