方法簽名
file.write(s: str) -> int # 回傳寫入的字元數(文字模式)或位元組數(二進制模式)
關鍵特性
- 不自動加入換行符,需自行在字串包含
\n。
- 受緩衝區影響,資料可能暫留記憶體,需
flush() 或 close() 強制寫入磁碟。
- 二進制模式(
"wb"、"r+b")需傳入 bytes 型別。
範例:在檔案末尾追加一行
#!/usr/bin/env python3
with open("foo.txt", "r+") as f:
print(f"檔案: {f.name}")
# 移至檔案末尾
f.seek(0, 2) # whence=2 代表 SEEK_END
f.write("This is 6th line\n")
# 從頭讀取驗證
f.seek(0)
for i, line in enumerate(f):
print(f"Line {i}: {line.rstrip()}")
輸出結果
檔案: foo.txt
Line 0: This is 1st line
Line 1: This is 2nd line
Line 2: This is 3rd line
Line 3: This is 4th line
Line 4: This is 5th line
Line 5: This is 6th line
進階模式對照表
| 模式 | 可讀 | 可寫 | 建立新檔 | 截斷既有 | 指標初始位置 |
r+ | ✓ | ✓ | ✗ | ✗ | 開頭 |
w+ | ✓ | ✓ | ✓ | ✓ | 開頭 |
a+ | ✓ | ✓ | ✓ | ✗ | 末尾 |
wb | ✗ | ✓ | ✓ | ✓ | 開頭 |
最佳實踐
- 優先使用
with open(...) as f: 確保自動 close()/flush()。
- 大量寫入時,累積在列表再
writelines() 或 write(''.join(...)),減少系統呼叫。
- 關鍵資料(交易日誌等)寫入後立即
f.flush(); os.fsync(f.fileno()) 強制落盤。
- 文字模式指定
encoding="utf-8" 避免平台預設編碼差異。