抱歉,这个问题很愚蠢,但是我有点像python新手。
我正在尝试将python 2.7代码库移植到python 3.4 ...
我发现了此代码段,该代码段应在打包的应用程序内的csv文件上进行迭代。
尽管PyDev告诉我,pkg_resources.respource_stream是未定义的,但第一行似乎起作用,导致第三行引发此错误:_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)
io = pkg_resources.resource_stream(__name__, "data.csv")
c = csv.reader(io)
for record in c:
#doStuff
Run Code Online (Sandbox Code Playgroud)
我尝试将方法切换到resource_string,ResourceManager.resourceStream等,但是我得到的只是不同的错误。
pkg_resources.resource_stream返回以二进制模式读取的流;它只是返回读取的字节,而不会尝试使用特定的编码对其进行解码。
该codecs模块中提供了大多数用于编码和解码文本的工具。要将二进制阅读器转换为给定特定编码的文本阅读器,请使用codecs.getreader。由于您自己捆绑了此文件,因此您应该知道编码,该编码可能应该是UTF-8。所以你会写:
io = pkg_resources.resource_stream(__name__, "data.csv")
utf8_reader = codecs.getreader("utf-8")
c = csv.reader(utf8_reader(io))
for record in c:
# doStuff
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
298 次 |
| 最近记录: |