python elementtree乱码_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

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字符.发生什么事?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值