使用seek()方法報錯:“io.UnsupportedOperation: can't do nonzero cur-relative seeks”錯誤的原因
阿新 • • 發佈:2017-10-08
pac nbsp mar std orm ack logs 打開文件 off
在使用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”錯誤的原因