【问题标题】:Python3: StringIO and Elementree encodingPython3:StringIO 和 Elementree 编码
【发布时间】:2013-11-12 01:41:31
【问题描述】:

迁移到 Python 3 xml.etree.ElementTree 的 write() 无法按预期工作。

我需要使以下代码与 Python3 一起工作:

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

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

py3 的问题在于它将 fileobj 视为字节,因此无法将其写入 StringIO。然后在检查ElementTree docutmentation 之后,看来我必须使用encoding='unicode',这在 py3 中工作得很好,但在 py2 中失败了。

现在,有办法让它与 py2 和 py3 一起使用,还是我必须使用 io.BytesIO 作为 py3 的解决方法,还是我应该根据 python 版本使用不同的编码?

这里最好的解决方案是什么?

【问题讨论】:

    标签: python unicode python-3.x elementtree stringio


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-08
      • 2020-01-25
      • 1970-01-01
      • 1970-01-01
      • 2019-03-16
      • 2017-06-19
      • 2023-04-11
      • 2020-09-14
      相关资源
      最近更新 更多