python – 将文件写入文件时出现XML编码错误
发布时间:2020-12-20 13:24:48 所属栏目:Python 来源:网络整理
导读:我想我正在遵循正确的方法,但我仍然遇到编码错误: from xml.dom.minidom import Documentimport codecsdoc = Document()wml = doc.createElement("wml")doc.appendChild(wml)property = doc.createElement("property")wml.appendChild(property)description
我想我正在遵循正确的方法,但我仍然遇到编码错误:
from xml.dom.minidom import Document import codecs doc = Document() wml = doc.createElement("wml") doc.appendChild(wml) property = doc.createElement("property") wml.appendChild(property) descriptionNode = doc.createElement("description") property.appendChild(descriptionNode) descriptionText = doc.createTextNode(description.decode('ISO-8859-1')) descriptionNode.appendChild(descriptionText) file = codecs.open('contentFinal.xml','w',encoding='ISO-8859-1') file.write(doc.toprettyxml()) file.close() 描述节点包含ISO-8859-1编码中的一些字符,这是由元标记中的自身指定的编码.但是当doc.toprettyxml()开始在文件中写入时,我得到了以下错误: Traceback (most recent call last): File "main.py",line 467,in <module> file.write(doc.toprettyxml()) File "C:Python27libxmldomminidom.py",line 60,in toprettyxml return writer.getvalue() File "C:Python27libStringIO.py",line 271,in getvalue self.buf += ''.join(self.buflist) UnicodeDecodeError: 'ascii' codec can't decode byte 0xe1 in position 10: ordinal not in range(128) 为什么我会收到此错误,因为我使用相同的标准进行解码和编码? 编辑 我的脚本文件中有以下减速: #!/usr/bin/python # -*- coding: utf-8 -*- 可能这是冲突的吗? 解决方法
好的,我找到了解决方案.当数据处于其他外语时,您只需要在xml头中定义正确的编码.你不需要在file.write(doc.toprettyxml(encoding =’ISO-8859-1′))中描述编码,即使你打开一个文件来写file = codecs.open(‘contentFinal.xml’,’ w’,encoding =’ISO-8859-1′).以下是我使用的技术.可能这不是一种专业方法,但对我有用.
file = codecs.open('abc.xml','w') xm = doc.toprettyxml() xm = xm.replace('<?xml version="1.0" ?>','<?xml version="1.0" encoding="ISO-8859-1"?>') file.write(xm) file.close() 可能有一种方法在标头中设置默认编码但我找不到它.以上方法不会在浏览器上带来任何错误,所有数据都能完美显示. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |