python2将str类型与unicode类型字符串写入文件的编码问题

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

1、如果字符串是str类型

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

2、如果字符串是unicode类型

# -*- coding:utf-8 -*-
txtFile=u"今天天气不错"
txtFile=txtFile.encode('utf-8')  #unicode字符串转换成utf8
f = open("1.txt", "wb")
f.write(txtFile)
f.close()

#如果不转换,会出现UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-5: ordinal not in range(128)

 NOTE:

python2 默认编码是ASCII码,使用   # -*- coding:utf-8 -*-    将文件编码为utf-8,即str类型。

Python3中默认是unicode

a = u'今天天气不错'             a 是unicode类型
b = a.encode('utf-8')            b 是str类型                         Unicode --> encode编码 --> GBK/UTF-8
a = b.decode('utf-8')            a 是unicode类型                 UTF-8 --> decode 解码 --> Unicode

使用type查看编码形式,unicode是‘unicode’,    gbk和utf-8是‘str或bytes’。



 
原文地址:https://www.cnblogs.com/taoyuanming/p/10870739.html