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.

1

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks it worked but i need to made some modification in obis_file.write(xml).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.