简体   繁体   中英

Python3: StringIO and Elementree encoding

With migration to Python 3 xml.etree.ElementTree's write() doesn't work as expected.

I need to make the following code work with Python3:

tree = ET.ElementTree(root)
fileobj = StringIO()

tree.write(fileobj, encoding="utf-8")

The problem with py3 is that it treats fileobj as bytes and therefore fails to write it to StringIO. Then after checking ElementTree docutmentation it appears I have to use encoding='unicode' and this works just fine in py3 but fails with py2.

Now, it there a way to make it work with both py2 and py3 or do I have to use io.BytesIO as a workaround for py3, or shall I use different encoding based on python version?

What is the best solution here?

最后,我决定对py2和py3都使用io.BytesIO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM