python – 用ElementTree写入带有utf-8数据的xml utf-8文件

前端之家收集整理的这篇文章主要介绍了python – 用ElementTree写入带有utf-8数据的xml 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'Töreboda' #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()
原文链接:https://www.f2er.com/python/185826.html

猜你在找的Python相关文章