Python在打开文件的同时规定编码

规定编码

代码

# 在打开文件的同时规定编码
'''
如果你正在使用 Python 2,我们又希望能够读写其它非英语语言,我们需要使用
unicode 类型,它全都以字母 u 开头,例如 u"hello world" 。

>>> u"hello world"
'hello world'
'''

# encoding = utf-8
import io

f = io.open("abc.txt", "wt", encoding="utf-8")
f.write(u"Imagine non-English language here")
f.close()

text = io.open("abc.txt", encoding="utf-8").read()
print(text)

运行结果

Imagine non-English language here
打赏
评论区
头像
文章目录