python - UnicodeDecodeError : 'ascii' codec can't decode byte 0xc2

标签 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:仅使用脚本第一行的特殊注释

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。

最佳答案

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

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

关于python - UnicodeDecodeError : 'ascii' codec can't decode byte 0xc2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16508539/

相关文章:

python - python项目中的Liquibase集成

python - 使用 pyparsing 在 python 中解析文本文件

python - 打乱数据行时分类器准确率达到 100%

python - 计数如果 : job is in a certain time interval

python - 不同 linux 发行版上的 python 系统属性 "__file__"不一致

python - Pandas 转出独特的专栏

python - 如何在一台 Apache 服务器上部署多个 Python 2 和 3 Django 项目?

python - 如何循环遍历城市列表以计算它们之间的距离

python - python中的重复导入路径模式

python - 如何将值附加到 AWS DynamoDB 上的列表属性?