【问题标题】:Reading UTF-8 file with codecs in IronPython在 IronPython 中使用编解码器读取 UTF-8 文件
【发布时间】:2012-04-12 12:10:27
【问题描述】:

我有一个以 UTF-8 编码的 .csv 文件,其中包含拉丁文和西里尔文符号。

;F1;F2;abcdefg3;F200
;ABSOLUTE;NOMINAL;NOMINAL;NOMINAL
o1;1;USA;Новосибирск;1223

我正在尝试在 IronPython 2.7.1 中执行以下脚本:

import codecs

f = codecs.open(r"file.csv", "rb", "utf-8")
f.next()

在执行 f.next() 期间发生异常:

Traceback (most recent call last):
  File "c:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\Extensions\Microsoft\Python Tools for Visual Studio\1.1\visualstudio_py_repl.py", line 492, in run_file_as_main
    code.Execute(self.exec_mod)
  File "<string>", line 4, in <module>
  File "C:\Program Files\IronPython 2.7.1\Lib\codecs.py", line 684, in next
    return self.reader.next()
  File "C:\Program Files\IronPython 2.7.1\Lib\codecs.py", line 615, in next
    line = self.readline()
  File "C:\Program Files\IronPython 2.7.1\Lib\codecs.py", line 530, in readline
    data = self.read(readsize, firstline=True)
  File "C:\Program Files\IronPython 2.7.1\Lib\codecs.py", line 477, in read
    newchars, decodedbytes = self.decode(data, self.errors)
UnicodeEncodeError: ('unknown', '\x00', 0, 1, '')

同时在 CPython 2.7 中,脚本可以正常工作。在 IronPython 2.7.1 中,以下脚本也可以正常工作:

import codecs

f = codecs.open(r"file.csv", "rb", "utf-8")
f.readlines()

有人知道是什么原因导致了这种奇怪的行为吗?

【问题讨论】:

    标签: python encoding csv utf-8 ironpython


    【解决方案1】:

    看起来这可能是next() 处理编解码器的错误。能否请open an issue附上要复制的文件?

    【讨论】:

      【解决方案2】:

      “rb”参数可能有问题,请尝试使用“r”

      f = codecs.open(r"file.csv", "r", "utf-8")
      

      【讨论】:

      • 我已尝试删除“b”。异常消失了,但西里尔符号被解码错误。此外,根据文档,StreamReader 接受流,该流必须是打开以读取(二进制)数据的类似文件的对象。
      猜你喜欢
      • 2016-08-14
      • 2016-02-22
      • 1970-01-01
      • 2011-07-07
      • 1970-01-01
      • 2011-07-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多