首页 > 编程语言 > 详细

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

时间:2019-05-04 12:51:25      阅读:596      评论:0      收藏:0      [点我收藏+]
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函数只能以二进制模式打开文件,才能正常运行,否则就会报出上面的错误

 

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()或零返回的偏移值。任何其他偏移值都会产生未定义的行为。

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

原文:https://www.cnblogs.com/bravesunforever/p/10808126.html

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