Python -- seek定位文件指針位置 錯誤 io.UnsupportedOperation: can't do nonzero cur-relative seeks錯誤


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()或零返回的偏移值。任何其他偏移值都會產生未定義的行為。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM