python – 用ElementTree写入带有utf-8数据的xml utf-8文件
发布时间:2020-11-18 07:47:21 所属栏目: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() (编辑:十堰站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- 在python中将函数的输出分配给空列表常量
- Python记录多个模块记录器不在主程序外工作
- Django Rest Framework上的全文搜索仅支持MYSQL?
- python exceptions.UnicodeDecodeError:’ascii’编解码器
- python – Django REST Framework中的camelCase POST数据
- python – Mac OS上“import cv”期间的“分段错误”
- python – Flask会话变量在请求之间不存在
- python – 来自提及的Tweepy用户ID
- Python合并两个字典的常用方法与效率比较
- Python中的hypot()方法使用简介