我正在使用Python创建XML文件,其中有一个字段需要放置文本文件的内容。我是通过以下方式实现的:
f = open ('myText.txt',"r")
data = f.read()
f.close()
root = ET.Element("add")
doc = ET.SubElement(root, "doc")
field = ET.SubElement(doc, "field")
field.set("name", "text")
field.text = data
tree = ET.ElementTree(root)
tree.write("output.xml")
然后我遇到了
UnicodeDecodeError
。我已经尝试在脚本顶部添加特殊注释# -*- coding: utf-8 -*-
,但仍然出现错误。我也已经尝试强制编码我的变量data.encode('utf-8')
,但仍然出现错误。我知道这个问题非常普遍,但是其他问题中得到的所有解决方案对我都没有用。更新:
回溯:只使用脚本第一行的特殊注释。
Traceback (most recent call last):
File "D:\Python\lse\createxml.py", line 151, in <module>
tree.write("D:\\python\\lse\\xmls\\" + items[ctr][0] + ".xml")
File "C:\Python27\lib\xml\etree\ElementTree.py", line 820, in write
serialize(write, self._root, encoding, qnames, namespaces)
File "C:\Python27\lib\xml\etree\ElementTree.py", line 939, in _serialize_xml
_serialize_xml(write, e, encoding, qnames, None)
File "C:\Python27\lib\xml\etree\ElementTree.py", line 939, in _serialize_xml
_serialize_xml(write, e, encoding, qnames, None)
File "C:\Python27\lib\xml\etree\ElementTree.py", line 937, in _serialize_xml
write(_escape_cdata(text, encoding))
File "C:\Python27\lib\xml\etree\ElementTree.py", line 1073, in _escape_cdata
return text.encode(encoding, "xmlcharrefreplace")
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 243: ordina
l not in range(128)
回溯:使用.encode('utf-8')
Traceback (most recent call last):
File "D:\Python\lse\createxml.py", line 148, in <module>
field.text = data.encode('utf-8')
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 227: ordina
l not in range(128)
我使用了.decode('utf-8')
,错误信息没有出现并且成功创建了XML文件。但问题是我的浏览器无法查看这个XML文件。
decode
而不是encode
。 - Mark Ransom# -*- coding: utf-8 -*-
只是为了在 Python 源代码中插入非 ASCII 字符。它不会以任何方式影响字符串的编码/解码。此外,如果文件myText.txt
不是 ASCII 格式,则应使用codecs.open
并提供正确的编码方式:codecs.open('myText.txt', 'r', 'utf-8')
。 - Bakuriutree.write
中添加编码(请参阅文档)。 - Thomas Fenzl