【问题标题】:Python 2.6: Unicode issue when writing to filePython 2.6:写入文件时出现 Unicode 问题
【发布时间】:2014-07-07 23:19:03
【问题描述】:

使用极其旧版本的 Python (2.6),我在将数据写入文件时遇到了 Unicode 编码问题:

t = tempfile.NamedTemporaryFile(mode = "w+b")
res = text.encode("UTF-8")
t.write(res)
print t.read()

在这个简单的例子中,text 是一个<unicode> 类型。我将其转换为以 UTF-8 编码的<str> 类型,并将其写入输出文件。但是,当我读入文件时,数据已完全损坏,表明发生了某种编码错误。

使用更高版本的 Python (Python 2.7),这可以完美运行。导致此问题的 Python 2.6 究竟有何不同?

【问题讨论】:

  • repr(t.read()) 之前添加t.seek(0)t.flush() 不会受到伤害,尽管t.seek 应该足够了)。添加t.close()“导致此问题的 Python 2.6 到底有什么不同?” -- 尝试将text 最小化(一个或两个 Unicode 代码点),例如,使用二进制搜索(text = text [:len(text)//2], etc) 或使用diff, cmp 比较 Python 2.7 和 Python 2.6 的结果。

标签: python python-2.7 unicode python-2.6


【解决方案1】:

当您向文件写入内容并从同一文件中读取内容时,会读取文件末尾之后的内容。在某些操作系统(Windows)上,这会导致垃圾。您必须返回 0 才能再次读取文件。

【讨论】:

    【解决方案2】:

    我不确定这是否适用于 python 2.6,但我最近不得不处理一个类似的问题,但我使用了类似的东西并且它成功了

    res = text.encode('utf-8', 'replace')

    这应该可以解决问题,因为错误将被替换为 utf-8。我为我工作。

    【讨论】:

      猜你喜欢
      • 2018-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多