2015-04-08 59 views
0

我想从python(2.7)使用xml.append函数编写一个xml文件。Python 2.7编码

我有一个字符串“Frédéric”需要写入xml文件作为值之一。 我想在此字符串上使用unicode函数,然后编码函数以写入文件。

a ="Frédéric" 
unicode(a, 'utf8') 

通过我收到错误消息“ASCII”编解码器

我已经通过其他计算器帖子对于这种情况了9' 位不能解码字节0xe9的建议是,增添的unicode在字符串之前。

a = u'Frédéric' 
a.encode('utf8') 

以来,我的“一”变量将是动态的(它可以从一个列表中的任何值),我需要使用unicode功能。

有什么建议吗?

谢谢

+2

在脚本的顶部添加'# - coding:utf8 - #'。 –

+0

...以及如何在开始时构建列表?它应该有所有的unicode字符串,比如'[u“Frédéric”,“José”,...]' – Selcuk

回答

1

也许下面的帮助。您可以使用编解码器在使用utf-8时保存XML字符串。

import codecs 


def save_xml_string(path, xml_string): 
    """ 
    Writes the given string to the file associated with the given path. 
    :param path: 
     Path to the file to write to. 
    :param xml_string: 
     The string to be written 
    :return: 
     nothing 
    """ 
    output_file = codecs.open(path, "w", "utf-8") 
    output_file.write(xml_string) 
    output_file.close()