檔案 I/O 是程式設計基礎。本文系統講解 Python 檔案操作:open() 模式參數、with 上下文管理器、文字/二進制模式、編碼轉換、codecs 模組、大檔案分塊讀取、file-like Object 介面概念,提供生產級最佳實踐。
f = open(file, mode='r', encoding=None, errors='strict', buffering=-1)
| 模式 | 說明 | 指標初始位置 |
|---|---|---|
r | 唯讀(預設) | 開頭 |
w | 寫入,截斷既有檔案 | 開頭 |
a | 附加,不截斷 | 結尾 |
r+ | 讀寫 | 開頭 |
w+ | 讀寫,截斷 | 開頭 |
a+ | 讀寫,附加 | 結尾 |
b | 二進制模式(搭配上述) | - |
t | 文字模式(預設) | - |
# 一次性讀取全部(小檔案)
with open('/path/to/file', 'r', encoding='utf-8') as f:
content = f.read()
# 逐行讀取(大檔案、記憶體友善)
with open('/path/to/file', 'r', encoding='utf-8') as f:
for line in f:
process(line.strip())
# 指定大小分塊讀取
with open('/path/to/file', 'r') as f:
while True:
chunk = f.read(8192)
if not chunk:
break
process(chunk)
# readlines() 返回列表(適合配置檔)
with open('config.ini') as f:
for line in f.readlines():
print(line.strip())
# 文字模式
with open('/path/to/file', 'w', encoding='utf-8') as f:
f.write('Hello, world!')
f.writelines(['line1\n', 'line2\n'])
# 二進制模式(圖片、影片、序列化資料)
with open('/path/to/image.jpg', 'wb') as f:
f.write(binary_data)
# 錯誤示範:預設編碼依賴平台
with open('gbk.txt', 'r') as f:
print(f.read()) # 可能亂碼
# 正確:明確指定編碼
with open('gbk.txt', 'r', encoding='gbk') as f:
print(f.read())
# 二進制讀取 + 手動解碼
with open('gbk.txt', 'rb') as f:
content = f.read().decode('gbk')
# codecs 模組:開啟時自動轉碼
import codecs
with codecs.open('gbk.txt', 'r', 'gbk') as f:
print(f.read()) # 直接得到 unicode
任何實作 read()/write() 的物件皆為 file-like:
StringIO / BytesIO:記憶體緩衝gzip.GzipFile:壓縮檔透明讀寫socket.makefile():網路流tempfile.TemporaryFile:臨時檔read(size) 即可| 錯誤 | 後果 | 正確做法 |
|---|---|---|
忘記 close() | 資源洩漏、資料未刷新到磁碟 | 永遠用 with |
大檔案 read() | 記憶體爆炸 (OOM) | 分塊讀取或逐行迭代 |
| 隱含編碼 | 跨平台亂碼 | 明確 encoding='utf-8' |
| 文字模式寫入二進制 | TypeError 或資料損壞 | 用 wb 模式 |
| 追加模式未換行 | 內容連在一起 | f.write('\n' + content) |
import os, tempfile
def atomic_write(path, data, mode='w', encoding='utf-8'):
dirname = os.path.dirname(path)
with tempfile.NamedTemporaryFile(mode=mode, encoding=encoding, dir=dirname, delete=False) as tf:
tf.write(data)
tempname = tf.name
os.rename(tempname, path) # 原子性替換(POSIX 保證)