python将一个字符串写入文件中的编码问题

python2将一个字符串写入文件中:

1、如果字符串是str类型

# -*- coding:utf-8 -*-
txtFile="今天天气不错"
name = "1.txt"
f = open(name, "wb")
f.write(txtFile)
f.close()

2、如果字符串是unicode类型

# -*- coding:utf-8 -*-
txtFile=u"今天天气不错"
txtFile=txtFile.encode('utf-8')
name = "1.txt"
f = open(name, "wb")
f.write(txtFile)
f.close()

知识点:python2默认编码是ASCII码,Python3中默认是unicode

python2默认编码是ASCII码,Python3中默认是unicode
a = u'今天天气不错' a 是unicode类型
b = a.encode('utf-8') b 是str类型,即utf-8类型, 表示将a 转变成utf-8类型
a = b.decode('utf-8') a 是unicode类型, 表示将b 以utf-8 的形式解码成unicode
手动转码过程
UTF-8 --> decode 解码 --> Unicode
Unicode --> encode编码 --> GBK / UTF - 8
使用type查看编码形式,unicode是‘unicode’, gbk和utf-8是‘str或bytes’。
 

猜你喜欢

转载自www.cnblogs.com/taoyuanming/p/10870739.html