Tengo un problema al generar un archivo .SVG con Python3 y ElementTree.
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()La función et.tostring(doc) genera el TypeError "el argumento write() debe ser str, no bytes". No entiendo ese comportamiento, "et" debería convertir el ElementTree-Element en una cadena. Funciona en python2, pero no en python3. ¿Qué hice mal?
Resulta que tostring , a pesar de su nombre , realmente devuelve un objeto cuyo tipo es bytes .
Han sucedido cosas más extrañas. De todos modos, aquí está la prueba:
>>> from xml.etree.ElementTree import ElementTree, tostring >>> import xml.etree.ElementTree as ET >>> element = ET.fromstring("<a></a>") >>> type(tostring(element)) <class 'bytes'>Tonto, ¿no?
Afortunadamente puedes hacer esto:
>>> type(tostring(element, encoding="unicode")) <class 'str'> Sí, todos pensamos que la ridiculez de los bytes y esa antigua codificación obsoleta de más de cuarenta años llamada ascii estaba muerta.
Y no me hagan empezar con el hecho de que llaman "unicode" una codificación !!!!!!!!!!!
El archivo de salida debe estar en modo binario.
f = open('sample.svg', 'wb')Tratar:
f.write(et.tostring(doc).decode(encoding))Ejemplo:
f.write(et.tostring(doc).decode("utf-8"))