Python 2 中直接用 open() 寫入中文會報 UnicodeEncodeError,必須用 codecs.open() 指定編碼。Python 3 內建 open(encoding=...) 已原生支持。本文給出兩版本通用的最佳實踐。
# -*- coding: utf-8 -*-
import codecs
content = u'你好,腳本之家 jb51.net'
with codecs.open('c:/1.txt', 'w', 'utf-8') as f:
f.write(content)
# -*- coding: utf-8 -*-
content = '你好,腳本之家 jb51.net' # Python 3 字符串默認 Unicode
with open('c:/1.txt', 'w', encoding='utf-8') as f:
f.write(content)
# -*- coding: utf-8 -*-
import sys
import codecs if sys.version_info[0] == 2 else None
content = u'你好,腳本之家 jb51.net'
if sys.version_info[0] == 2:
with codecs.open('c:/1.txt', 'w', 'utf-8') as f:
f.write(content)
else:
with open('c:/1.txt', 'w', encoding='utf-8') as f:
f.write(content)
| 版本 | 字符串字面量 | 打開文件 | 寫入 |
|---|---|---|---|
| Python 2 | 必須 u'' 前綴 | codecs.open(path, 'w', 'utf-8') | 寫入 unicode 對象 |
| Python 3 | 默認即 Unicode | open(path, 'w', encoding='utf-8') | 寫入 str 對象 |
u'':Python 2 下 '中文' 是字節串,寫入時按默認 ASCII 編碼報錯。f.write(b'bytes') 需二進制模式 'wb',文本模式只接受 str。# -*- coding: utf-8 -*-。u''(Py2/3 兼容)。io.open(from io import open),Py2/3 行為一致。encoding='utf-8'(或 'utf-8-sig' 兼容 BOM)。with 上下文管理器自動關閉。做對編碼,中英文混寫不再是痛點。