file.seek()方法标准格式是:seek(offset,whence=0)offset:开始的偏移量,也就是代表需要移动偏移的字节数, whence:给offset参数一个定义,表示要从哪个位置开始偏移;0代表从文件开头开始算起,1代表从当前位置开始算起,2代表从文件末尾算起。默认为0
whence 的默认参数是0。
whence 还有两种情况 是1,或者2:
1的时候,相对当前坐标的移动,可以是正的也可以是负的。
2的时候相对于文件结束的移动,通常应该是负的。
f=open(‘d.txt‘,‘rb‘)
for i in f:
offs=-3
n=1
while True:
f.seek(offs,2)
print(f‘你好啊这是第{n}次‘,f.readline(),offs)
data=f.readlines()
print(‘data‘,data)
if len(data) > 1:
print(‘最后一行‘,data[-1].decode(‘utf-8‘))
break
offs*=2
n += 1
输出:
f=open(‘d.txt‘,‘rb‘)
for i in f:
offs=-3
n=1
while True:
f.seek(offs,2)
print(f‘你好啊这是第{n}次‘,f.readline(),offs)
data=f.readlines()
print(‘data‘,data)
if len(data) > 1:
print(‘最后一行‘,data[-1].decode(‘utf-8‘))
break
offs*=2
n += 1
文件 d.txt:
123hello
123hello
123asdfasdfasdf
哼123456789哈
示例2:
f=open(‘seek.txt‘,‘rb‘)
print(f.tell())
f.seek(-5,2)
print(f.read())
print(f.tell())
f.seek(3,1)
print(f.read())
print(f.tell())
输出:
f=open(‘seek.txt‘,‘rb‘)
print(f.tell())
f.seek(-5,2)
print(f.read())
print(f.tell())
f.seek(3,1)
print(f.read())
print(f.tell())
seek.txt文件
hello
你好王八蛋
123456
abcdef
读取文件最后一行 f.seek(offset,whence=0)
原文:https://www.cnblogs.com/heris/p/14763376.html