在Python中,使用file.write写入文件时出现错误。UnicodeEncodeError
在Python中,使用file.write写入文件时出现错误。UnicodeEncodeError
我从未处理过字符串的编码和解码,所以在这方面我是个新手。当我尝试使用Python的file.write将从另一个文件中读取的内容写入临时文件时,我收到了一个UnicodeEncodeError错误。错误信息如下:\n
UnicodeEncodeError: 'ascii' codec can't encode character u'\u201c' in position 41333: ordinal not in range(128)
\n以下是我的代码。我正在读取一个XML文件,并从\"mydata\"标签中获取文本。然后,我遍历mydata以查找包含CDATA的元素中的文本(lua代码)。\n
parser = etree.XMLParser(strip_cdata=False) root = etree.parse(myfile.xml, parser) data = root.findall('./mydata') # 遍历列表以查找包含CDATA的元素中的文本(lua代码) for item in myData: myCode = item.text # 将myCode写入临时文件 tempDirectory = tempfile.mkdtemp(suffix="", prefix="TEST_THIS_") file = open(tempDirectory + os.path.sep + "myCode.lua", "w") file.write(myCode + "\n") file.close()
\n当我执行以下代码时,它在以下行出现UnicodeEncodeError错误:\n
file.write(myCode + "\n")
\n请问我应该如何正确地编码和解码这段代码?
Python2.7的open函数不像Python3那样透明地处理Unicode字符。关于这一点有很多详细的文档,但是如果你想直接写入Unicode字符串而不解码它们,你可以尝试以下方法:
<<< import codecs
<<< f = codecs.open(filename, 'w', encoding='utf8')
<<< f.write(u'\u201c')
作为对比,下面是发生错误的方式:
<<< f = open(filename, 'w')
<<< f.write(u'\u201c')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\u201c' in position 0: ordinal not in range(128)
问题的原因是Python2.7的open函数默认使用ASCII编码,而ASCII编码无法处理Unicode字符。解决方法是使用codecs模块的open函数,并指定编码为utf8。
这篇文章介绍了在Python2.7中使用file.write函数写入文件时出现UnicodeEncodeError的原因以及解决方法。