iggy
iggy

Reputation: 31

TypeError: Can't convert 'bytes' object to str implicitly in python

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.

Upvotes: 1

Views: 2107

Answers (1)

poke
poke

Reputation: 387637

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)

Upvotes: 3

Related Questions