python – 用ElementTree写入带有utf-8数据的xml utf-8文件
发布时间:2020-11-18 06:55:50 所属栏目:Python 来源:互联网
导读:我试图使用ElementTree使用utf-8编码的数据编写一个xml文件,如下所示: #!/usr/bin/python # -*- coding: utf-8 -*-
|
我试图使用ElementTree使用utf-8编码的数据编写一个xml文件,如下所示: #!/usr/bin/python
# -*- coding: utf-8 -*-
import xml.etree.ElementTree as ET
import codecs
testtag = ET.Element('unicodetag')
testtag.text = u'Treboda' #The o is really ö (o with two dots over). No idea why SO dont display this
expfile = codecs.open('testunicode.xml',"w","utf-8-sig")
ET.ElementTree(testtag).write(expfile,encoding="UTF-8",xml_declaration=True)
expfile.close()
这样会产生错误 Traceback (most recent call last):
File "unicodetest.py",line 10,in <module>
ET.ElementTree(testtag).write(expfile,xml_declaration=True)
File "/usr/lib/python2.7/xml/etree/ElementTree.py",line 815,in write
serialize(write,self._root,encoding,qnames,namespaces)
File "/usr/lib/python2.7/xml/etree/ElementTree.py",line 932,in _serialize_xml
write(_escape_cdata(text,encoding))
File "/usr/lib/python2.7/codecs.py",line 691,in write
return self.writer.write(data)
File "/usr/lib/python2.7/codecs.py",line 351,in write
data,consumed = self.encode(object,self.errors)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 1: ordinal not in range(128)
使用“us-ascii”编码代替工作正常,但不保留数据中的unicode字符.发生什么事? 解决方法codecs.open希望将Unicode字符串写入文件对象,它将处理UTF-8的编码. ElementTree的写入将Unicode字符串编码为UTF-8字节字符串,然后将其发送到文件对象.由于文件对象需要Unicode字符串,所以使用默认的ascii编解码器将字节串强制转换为Unicode,并导致UnicodeDecodeError.只要这样做: #expfile = codecs.open('testunicode.xml',"utf-8-sig")
ET.ElementTree(testtag).write('testunicode.xml',xml_declaration=True)
#expfile.close() (编辑:哈尔滨站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
