| 概念 | 說明 |
| 字元集 | 字元與代碼點對應表 (Unicode: U+0000 ~ U+10FFFF) |
| 編碼 | 代碼點 → 位元組序列的規則 (UTF-8, UTF-16, GBK, Big5, Latin-1...) |
| Python 3 字串 | str = Unicode 代碼點序列 (抽象、無編碼) |
| Python 3 位元組 | bytes = 0-255 整數序列 (具體儲存/傳輸格式) |
| 轉換 | str.encode(encoding) → bytes、bytes.decode(encoding) → str |
讀寫檔案:正確姿勢
1. 寫入 UTF-8 (推薦預設)
# 文字模式:自動處理換行、編碼
with open('output.txt', 'w', encoding='utf-8') as f:
f.write('中文內容\nEnglish\n')
# 二進制模式:完全控制位元組
with open('output.bin', 'wb') as f:
f.write('中文'.encode('utf-8'))
f.write(b'\n')
2. 讀取:明確指定編碼
# 讀取 UTF-8
with open('input.txt', 'r', encoding='utf-8') as f:
text = f.read()
# 讀取 GBK/Big5 (中文舊系統)
with open('legacy.txt', 'r', encoding='gbk') as f: # 或 'big5', 'cp950'
text = f.read()
# 自動偵測編碼 (需安裝 chardet 或 charset-normalizer)
import charset_normalizer
with open('unknown.txt', 'rb') as f:
raw = f.read()
result = charset_normalizer.from_bytes(raw).best()
text = str(result) if result else raw.decode('utf-8', errors='replace')
BOM (Byte Order Mark) 處理
UTF-8 BOM: EF BB BF (三位元組)。部分 Windows 工具 (記事本舊版) 預設加 BOM。
import codecs
def read_utf8_with_bom(path):
with open(path, 'rb') as f:
raw = f.read()
# 移除 BOM
if raw.startswith(codecs.BOM_UTF8):
raw = raw[len(codecs.BOM_UTF8):]
return raw.decode('utf-8')
# 或使用 codecs.open (自動處理 BOM)
with codecs.open('file.txt', 'r', 'utf-8-sig') as f: # utf-8-sig 自動移除 BOM
text = f.read()
Python 2 vs Python 3 關鍵差異
| 特性 | Python 2 | Python 3 |
str | 位元組串列 | Unicode 字串 |
unicode | Unicode 字串 | 不存在 |
bytes | str 別名 | 位元組串列 |
| 預設編碼 | ASCII (sys.getdefaultencoding()) | UTF-8 (locale 相關) |
| open() 回傳 | 檔案物件 (位元組) | TextIOWrapper (文字模式) |
原文 reload(sys); sys.setdefaultencoding() | 可用 (但極不推薦) | Python 3 移除此 API,不可用 |
設定預設編碼:正確與錯誤的方式
❌ 錯誤:修改 sys.setdefaultencoding
# Python 2 僅有的駭客手法,Python 3 已移除
import sys
reload(sys)
sys.setdefaultencoding('utf-8') # 破壞核心庫假設,導致不可預期錯誤
✅ 正確:環境變數與 locale
# Linux/macOS 終端機設定 (永久生效,寫入 ~/.bashrc 或 ~/.zshrc)
export LANG=en_US.UTF-8
export LC_ALL=en_US.UTF-8
# Windows 控制台
chcp 65001 # 切換代碼頁為 UTF-8
# Python 程式碼中:不依賴預設編碼,永遠明確指定
with open(fname, 'r', encoding='utf-8') as f: ...
✅ 正確:sitecustomize.py (僅限極特殊舊專案遷移)
# 建立 site-packages/sitecustomize.py
import sys
# Python 3.7+ 可用 sys.setdefaultencoding 但極度不建議
# 此方法僅供理解原理,生產環境請勿使用
字串編碼轉換速查表
# 字面常數
s1 = '中文' # 原始碼檔案編碼決定內容 (建議檔案存為 UTF-8)
s2 = u'中文' # Python 2 相容語法,Py3 忽略 u 前綴
# 解碼:bytes → str
s3 = b'\xe4\xb8\xad\xe6\x96\x87'.decode('utf-8') # '中文'
s4 = '中文'.encode('utf-8') # b'\xe4\xb8\xad\xe6\x96\x87'
# 編碼:str → bytes
b1 = '中文'.encode('utf-8')
b2 = '中文'.encode('gbk')
b3 = '中文'.encode('utf-16')
# 圓周轉換
assert '中文'.encode('utf-8').decode('utf-8') == '中文'
# 錯誤處理策略
'中文'.encode('ascii', errors='strict') # 預設,拋出 UnicodeEncodeError
'中文'.encode('ascii', errors='ignore') # 直接丟棄無法編碼字元
'中文'.encode('ascii', errors='replace') # 替換為 ?
'中文'.encode('ascii', errors='xmlcharrefreplace') # 替換為 中文
b'\x80\x81'.decode('utf-8', errors='replace') # 解碼錯誤替換為
實戰:批次轉換檔案編碼
#!/usr/bin/env python3
"""將目錄下所有 .txt 從 GBK 轉為 UTF-8"""
import sys
import os
from pathlib import Path
def convert_encoding(src_dir, from_enc='gbk', to_enc='utf-8', pattern='*.txt'):
for filepath in Path(src_dir).rglob(pattern):
try:
content = filepath.read_text(encoding=from_enc)
# 備份原檔
backup = filepath.with_suffix(filepath.suffix + '.bak')
filepath.rename(backup)
# 寫入新編碼
filepath.write_text(content, encoding=to_enc)
print(f"已轉換: {filepath}")
except UnicodeDecodeError:
print(f"解碼失敗 (可能非 {from_enc}): {filepath}", file=sys.stderr)
# 還原備份
if backup.exists():
backup.rename(filepath)
except OSError as e:
print(f"IO 錯誤: {filepath} - {e}", file=sys.stderr)
if __name__ == '__main__':
if len(sys.argv) < 2:
print("用法: python convert_encoding.py <目錄> [來源編碼] [目標編碼]")
sys.exit(1)
convert_encoding(sys.argv[1], sys.argv[2] if len(sys.argv)>2 else 'gbk',
sys.argv[3] if len(sys.argv)>3 else 'utf-8')
總結
Python 3 以 Unicode 為核心,永遠在 I/O 邊界明確指定編碼 是黃金法則。避免依賴預設編碼、正確處理 BOM、善用 errors 參數容錯、使用 pathlib 簡化路徑操作。編碼問題 99% 來自「隱式假設」,顯式即治本。
copyright ©
萬盛學電腦網 all rights reserved