2017-02-27 145 views
2

在使用Python3和ElementTree生成.SVG文件時遇到了問題。在Python3中,ElementTree TypeError「write()參數必須是str,而不是字節」

from xml.etree import ElementTree as et 
    doc = et.Element('svg', width='480', height='360', version='1.1', xmlns='http://www.w3.org/2000/svg') 

    #Doing things with et and doc 

    f = open('sample.svg', 'w') 
    f.write('<?xml version=\"1.0\" standalone=\"no\"?>\n') 
    f.write('<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\"\n') 
    f.write('\"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n') 
    f.write(et.tostring(doc)) 
    f.close() 

的作用et.tostring(文件)生成類型錯誤 「寫()參數必須海峽,不是字節」。我不明白這種行爲,「et」應該將ElementTree元素轉換爲字符串?它適用於python2,但不適用於python3。我做錯了什麼?

+0

您是否檢查過文檔?查看[本頁](https://docs.python.org/3/library/xml.etree.elementtree.html)並搜索'tostring'。這有幫助嗎? –

+0

不是真的,它應該已經在utf-8字節串中解碼,但是python3似乎有問題 –

回答

6

事實證明,tostring儘管它的名字,真的確實返回一個對象,其類型爲bytes

奇怪的事情發生了。無論如何,這裏的證明:

>>> from xml.etree.ElementTree import ElementTree, tostring 
>>> import xml.etree.ElementTree as ET 
>>> element = ET.fromstring("<a></a>") 
>>> type(tostring(element)) 
<class 'bytes'> 

傻,是不是?

幸運的,你可以這樣做:

>>> type(tostring(element, encoding="unicode")) 
<class 'str'> 

是的,我們都以爲字節的荒謬和那個叫ascii古,四加歲的和過時的編碼已經死了。

不要讓我開始的事實,他們稱"unicode"編碼 !!!!!!!!!!!

+0

測試結果很有趣。當我看到'type(tostring(element))'的結果時,我無法相信它。然後看到結果因參數值的變化而改變。哇。那真的很奇怪。很好的問題。 –

2

嘗試:

f.write(et.tostring(doc).decode(encoding)) 

例子:

f.write(et.tostring(doc).decode("utf-8")) 
2

在寫入xml文件時指定字符串的編碼。

decode(UTF-8)write()。 例如:file.write(etree.tostring(doc).decode(UTF-8))

相關問題