萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python 檔案操作 tell() 方法:取得目前指標位置、配合 seek 實現隨機存取

方法簽名

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() 注意事項

  • 回傳值為「經編碼器處理後的不透明數字」,不可直接進行算術運算(如 tell() + 10 無意義)。
  • 僅能作為 seek(pos, 0) 的參數還原位置。
  • 若需字元級位置,請自行維護計數器或使用 io.StringIO。

二進制模式 tell()

回傳真實位元組位移,可自由加減、seek(),適合建立固定長度記錄索引。

進階:配合 mmap 實現零拷貝隨機存取

import mmap

with open("big.dat", "r+b") as f:
    mm = mmap.mmap(f.fileno(), 0)
    # 直接像 bytearray 操作
    mm[100:104] = b"NEW!"
    mm.flush()  # 同步回磁碟
copyright © 萬盛學電腦網 all rights reserved