码迷,mamicode.com
首页 > 其他好文 > 详细

使用seek()方法报错:“io.UnsupportedOperation: can't do nonzero cur-relative seeks”错误的原因

时间:2017-10-08 11:20:38      阅读:225      评论:0      收藏:0      [点我收藏+]

标签:open   let   class   font   relative   ted   size   blog   开始   

在使用seek()函数时,有时候会报错为  “io.UnsupportedOperation: can‘t do nonzero cur-relative seeks”,代码如下:

>>> f=open("aaa.txt","r+")    #以读写的格式打开文件aaa.txt
>>> f.read()    #读取文件内容
‘my name is liuxiang,i am come frome china‘
>>> f.seek(3,0)       #从开头开始偏移三个单位(偏移到“n”)
3
>>> f.seek(5,1)     #想要从上一次偏移到的位置(即“n”)再偏移5个单位
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
io.UnsupportedOperation: can‘t do nonzero cur-relative seeks

照理说,按照seek()方法的格式file.seek(offset,whence),后面的1代表从当前位置开始算起进行偏移,那又为什么报错呢?

这是因为,在文本文件中,没有使用b模式选项打开的文件,只允许从文件头开始计算相对位置,从文件尾计算时就会引发异常。将  f=open("aaa.txt","r+")  改成

f = open("aaa.txt","rb")   就可以了

 

改正后的代码如下图:

>>> f = open("aaa.txt","rb")
>>> f.seek(3,0)
3
>>> f.seek(5,1)
8

 

使用seek()方法报错:“io.UnsupportedOperation: can't do nonzero cur-relative seeks”错误的原因

标签:open   let   class   font   relative   ted   size   blog   开始   

原文地址:http://www.cnblogs.com/xisheng/p/7636736.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!