使用以下codecs
模块在程序的I / O边界处处理与Unicode之间的文本:
import codecs
with codecs.open(filename, 'r', encoding='utf8') as f:
text = f.read()
# process Unicode text
with codecs.open(filename, 'w', encoding='utf8') as f:
f.write(text)
io
现在建议使用该模块代替编解码器,并且该模块与Python 3的open
语法兼容,如果使用Python 3,则可以在open
不需要Python 2兼容性的情况下使用。
import io
with io.open(filename, 'r', encoding='utf8') as f:
text = f.read()
# process Unicode text
with io.open(filename, 'w', encoding='utf8') as f:
f.write(text)