UnicodeDecodeError:'ascii'编解码器无法解码字节0xc2

时间:2013-05-12 14:44:33

标签: python

我正在使用Python创建XML文件,我的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。

4 个答案:

答案 0 :(得分:64)

在使用之前,您需要将输入字符串中的数据解码为unicode,以避免编码问题。

field.text = data.decode("utf8")

答案 1 :(得分:12)

我在pywikipediabot遇到了类似的错误。 .decode方法是朝着正确方向迈出的一步,但对我而言,如果不添加'ignore'则无效:

fix_encoding = lambda s: s.decode('utf8', 'ignore')

答案 2 :(得分:7)

Python 2

导致错误是因为ElementTree在尝试将其写出时不希望找到非ASCII字符串设置XML。您应该将Unicode字符串用于非ASCII。可以使用字符串上的u前缀(即u'€')或使用适当的编码使用mystr.decode('utf-8')解码字符串来生成Unicode字符串。

最佳做法是在读取所有文本数据时对其进行解码,而不是解码中间程序。 io模块提供了open()方法,可以在读取时将文本数据解码为Unicode字符串。

使用ET.write()方法时,ElementTree会更快乐地使用Unicodes并正确编码。

此外,为了获得最佳兼容性和可读性,请确保在write()期间ET编码为UTF-8并添加相关标题。

假设您的输入文件是UTF-8编码的(0xC2是常见的UTF-8引导字节),将所有内容组合在一起,并使用with语句,您的代码应如下所示:

with io.open('myText.txt', "r", encoding='utf-8') as f:
    data = f.read()

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", encoding='utf-8', xml_declaration=True)

输出:

<?xml version='1.0' encoding='utf-8'?>
<add><doc><field name="text">data€</field></doc></add>

答案 3 :(得分:2)

#!/usr/bin/python

# encoding=utf8

尝试此操作以启动python文件

相关问题