file.tell() -> int
目前讀/寫指標的位元組位移(二進制模式)或經編碼器計算的位置(文字模式,不等於字元數)。
with open("foo.txt", "r+") as f:
print(f"檔案: {f.name}")
line = f.readline()
print(f"第一行: {line.rstrip()}")
pos = f.tell()
print(f"目前位置: {pos}") # 18 (含換行符)
檔案: foo.txt
第一行: This is 1st line
目前位置: 18
# 建立行號 → 位移 索引
def build_line_index(path):
index = []
with open(path, "rb") as f:
while True:
pos = f.tell()
line = f.readline()
if not line:
break
index.append(pos)
return index
# 使用索引隨機讀取第 N 行 (0-based)
def read_line_by_index(path, line_no, index):
with open(path, "rb") as f:
if line_no >= len(index):
return None
f.seek(index[line_no])
return f.readline().decode("utf-8").rstrip("\n")
tell() + 10 無意義)。seek(pos, 0) 的參數還原位置。io.StringIO。回傳真實位元組位移,可自由加減、seek(),適合建立固定長度記錄索引。
import mmap
with open("big.dat", "r+b") as f:
mm = mmap.mmap(f.fileno(), 0)
# 直接像 bytearray 操作
mm[100:104] = b"NEW!"
mm.flush() # 同步回磁碟