write() 方法將字串寫入檔案。因作業系統緩衝機制,資料可能暫時停留在記憶體,需呼叫 flush() 或 close() 確保落盤。本文詳細說明語法、參數、編碼、緩衝與實戰範例。
fileObject.write(str)
str:要寫入的字串(Python 3 為 str,Python 2 為 str/unicode,二進位模式下為 bytes)。\n。Python 3 回傳寫入的 字元數(文字模式)或 位元組數(二進位模式);Python 2 無回傳值(None)。
with open('foo.txt', 'w') as f:
f.write('Line 1\n')
f.write('Line 2\n')
f.write('Line 3\n')
with open('foo.txt', 'r') as f:
print(f.read())
# 輸出:
# Line 1
# Line 2
# Line 3
with open('foo.txt', 'a') as f:
f.write('Appended Line\n')
data = b'\x00\x01\x02\x03'
with open('binary.dat', 'wb') as f:
f.write(data)
with open('foo.txt', 'r+') as f:
f.seek(0, 2) # 移至檔案末尾 (whence=2 代表從末尾)
f.write('New Last Line\n')
#!/usr/bin/python
with open('foo.txt', 'w+') as f:
print("Name:", f.name)
# 預設內容
for i in range(1, 6):
f.write(f'Line {i}\n')
# 從末尾新增一行
f.seek(0, 2)
f.write('Line 6\n')
# 從頭讀回驗證
f.seek(0)
for i, line in enumerate(f):
print(f"Line No {i} - {line.rstrip()}")
# 輸出:
# Name: foo.txt
# Line No 0 - Line 1
# Line No 1 - Line 2
# Line No 2 - Line 3
# Line No 3 - Line 4
# Line No 4 - Line 5
# Line No 5 - Line 6
| 情境 | 說明 |
|---|---|
| 緩衝 | 資料先進 OS 緩衝區,flush() 強制寫入磁碟,close() 自動 flush。 |
| 編碼 | 文字模式預設編碼 locale.getpreferredencoding(),建議明確指定 encoding='utf-8'。 |
| 換行轉換 | Windows 文字模式下 \n 自動轉 \r\n,二進位模式不轉換。 |
| 非字串物件 | 需先轉字串(str(obj)、json.dumps、pickle 等),否則拋 TypeError。 |
write(str):單一字串。writelines(seq):字串可迭代物件(列表、產生器),不自動加換行,需自行在元素中包含 \n。write() 是檔案輸出最基礎的方法。掌握模式選擇(w/a/r+/wb)、編碼指定、緩衝控制與指標定位,能精準處理各類檔案寫入需求。