方法簽名
file.seek(offset, whence=0) -> int # 回傳新的絕對位置
whence 三種模式
| whence | 常數 | 含義 |
| 0 | io.SEEK_SET | 從檔案開頭計算 offset |
| 1 | io.SEEK_CUR | 從目前位置計算 offset |
| 2 | io.SEEK_END | 從檔案末尾計算 offset (通常為負值) |
範例:移至開頭重讀第一行
with open("foo.txt", "r+") as f:
line1 = f.readline()
print(f"第一次: {line1.rstrip()}")
f.seek(0, 0) # 回到開頭
line1_again = f.readline()
print(f"第二次: {line1_again.rstrip()}")
輸出
第一次: This is 1st line
第二次: This is 1st line
常見定位模式
f.seek(0) # 開頭
f.seek(0, 2) # 末尾 (追加位置)
f.seek(-100, 2) # 倒數 100 bytes
f.seek(100) # 絕對位移 100
f.seek(f.tell()+50) # 相對目前 +50 (等同 seek(50,1))
文字模式陷阱(重要)
- 文字模式下
offset 必須為 tell() 回傳的值 或 0。
- 任意整數 offset 可能落在多位元組字元中間 →
UnicodeDecodeError 或資料錯誤。
- 解決:改用二進制模式
"rb"/"r+b" 操作位元組位置,再手動解碼。
追加模式 ('a') 的特殊行為
seek() 雖可移動讀取指標,但寫入永遠發生在檔案末尾(OS 層面強制 O_APPEND)。
"a+" 可讀可寫,讀取可定位,寫入仍強制末尾。
不可定位的檔案物件
sys.stdin、socket.makefile()、gzip.GzipFile、http.client.HTTPResponse 等串流物件呼叫 seek() 會拋 io.UnsupportedOperation。
- 可用
f.seekable() 先行檢查。