首页 > 其他 > 详细

读取文件最后一行 f.seek(offset,whence=0)

时间:2021-05-13 13:33:10      阅读:16      评论:0      收藏:0      [点我收藏+]

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!