Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

362
Views
ElementTree TypeError "el argumento write() debe ser str, no bytes" en Python3

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?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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 !!!!!!!!!!!

over 4 years ago · Santiago Trujillo Report

0

El archivo de salida debe estar en modo binario.

 f = open('sample.svg', 'wb')
over 4 years ago · Santiago Trujillo Report

0

Tratar:

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

Ejemplo:

 f.write(et.tostring(doc).decode("utf-8"))
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!