如何在Python中读写unicode(UTF-8)文件?

现在推荐使用io模块,该模块与Python 3的开放语法兼容:以下代码用于读取和写入Python中的unicode(UTF-8)文件。

示例

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)