在使用seek()函数时,有时候会报错为 “io.UnsupportedOperation: can't do nonzero cur-relative seeks”,代码如下:
file = open("python13.txt", "w+", encoding="utf-8")
file.write("那年我们逝去的青春")
file.seek(3,1)#重新改变光标的位置 移动的量,相对位置 0开头 [1 当前位置 2 尾巴 不支持 只有二进制文件才支持这种方式]
照理说,按照seek()方法的格式file.seek(offset,whence),后面的1代表从当前位置开始算起进行偏移,那又为什么报错呢?
这是因为,在文本文件中,没有使用b模式选项打开的文件,只允许从文件头开始计算相对位置,从文件尾计算时就会引发异常。将file = open("python13.txt", "w+", encoding="utf-8") 改成file = open("python13.txt", "rb", encoding="utf-8") 问题解决