Python -- seek定位文件指针位置 错误 io.UnsupportedOperation: can't do nonzero cur-relative seeks错误...

该博客总结了Python中seek函数whence参数的使用规则。whence为0时,open函数以任何模式打开文件都能正常运行;为1和2时,open函数需以二进制模式打开。若未以二进制方式打开,offset无法用负值。还给出了Python官方文档的解释及原文链接。
f=open("E:/test/悯农.txt",'r')
str=f.read(17)
print("读取的数据是:",str)
position=f.tell()
print("当前位置:",position)


f.seek(4,0)  #从头开始,偏移4个字节
position=f.tell()
print("当前位置:",position)

 
f.seek(4,1)  #从当前位置开始,偏移4个字节
position=f.tell()
print("当前位置:",position)

f.seek(-4,2)
position=f.tell()
print("当前位置:",position)


f.close()

 

 

 

总结:

seek中whence参数的值:

0:open函数以r,w,带b的二进制模式,就是以任何模式打开文件,都能正常运行

1和2:open函数只能以二进制模式打开文件,才能正常运行,否则就会报出上面的错误

          如果没有以二进制b的方式打开,则offset无法使用负值(即向左侧移动)

 

Python的官方文档的解释:

链接地址:https://docs.python.org/3/tutorial/inputoutput.html?highlight=seek

>In text files (those opened without a b in the mode string), only seeks relative to the beginning of the file are allowed (the exception being seeking to the very file end with seek(0, 2)) and the only valid offset values are those returned from the f.tell(), or zero. Any other offset value produces undefined behaviour.

翻译:

    在文本文件中(那些在模式字符串中没有b打开的文件),只允许相对于文件的开头进行查找(例外情况是使用seek(0,2)查找文件的结尾),并且唯一有效的偏移值是从f.tell()或零返回的偏移值。任何其他偏移值都会产生未定义的行为。

转载于:https://www.cnblogs.com/bravesunforever/p/10808126.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值