1

Below is part of my python script that is giving error:

tree = ET.ElementTree(element_table)
xml = ET.tostring(element_table)
xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><?xml-  stylesheet type=\"text/xsl\" href=\".\/xsl\/brsdk.xsl\"?>" + xml
obis_file = open( "OBIS_Support_Chart_" + sdk_version.replace( ".","_" ) +   ".xml", "w" )
obis_file.write( xml.decode('utf8') )

The error flagged during running of the script is as below:

Traceback (most recent call last):
  File "parse.py", line 115, in <module>
    xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><?xml- stylesheet type=\"text/xsl\" href=\".\/xsl\/brsdk.xsl\"?>" + xml
TypeError: Can't convert 'bytes' object to str implicitly

What is problem there in the script? I am using Python 3.4.

poke
  • 369,085
  • 72
  • 557
  • 602
iggy
  • 31
  • 1
  • 8
  • possible duplicate of [Convert bytes to a Python string](http://stackoverflow.com/questions/606191/convert-bytes-to-a-python-string) – George Simms Aug 10 '15 at 06:14

1 Answers1

3

The documentation for ElementTree.tostring mentions this behavior:

Use encoding="unicode" to generate a Unicode string (otherwise, a bytestring is generated).

So in your case, since you don’t specify encoding="unicode" when calling tostring(), it returns a bytes object. Thus, when you try to concatenate a string with the previous output of tostring(), you try to concatenate a string with bytes, hence the error.

Specify the encoding to fix this:

xml = ET.tostring(element_table, encoding='unicode')

Since you then have an actual str object, you also no longer need to decode xml when writing to the file:

obis_file.write(xml)
poke
  • 369,085
  • 72
  • 557
  • 602