在Python2.7中有一个读取zip文件中的CSV文件的简单程序,但在Python3.2中没有

$ cat test_zip_file_py3k.py 
import csv, sys, zipfile

zip_file    = zipfile.ZipFile(sys.argv[1])
items_file  = zip_file.open('items.csv', 'rU')

for row in csv.DictReader(items_file):
    pass

$ python2.7 test_zip_file_py3k.py ~/data.zip

$ python3.2 test_zip_file_py3k.py ~/data.zip
Traceback (most recent call last):
  File "test_zip_file_py3k.py", line 8, in <module>
    for row in csv.DictReader(items_file):
  File "/home/msabramo/run/lib/python3.2/csv.py", line 109, in __next__
    self.fieldnames
  File "/home/msabramo/run/lib/python3.2/csv.py", line 96, in fieldnames
    self._fieldnames = next(self.reader)
_csv.Error: iterator should return strings, not bytes (did you open the file 
in text mode?)

因此,Python 3中的csv模块希望看到一个文本文件,但zipfile.ZipFile.open返回一个始终被视为二进制数据的zipfile.ZipExtFile.

如何在Python 3中实现这一点?

推荐答案

我只是注意到Lennart's answer不能与Python 3.1一起工作,但does可以与Python 3.2一起工作.他们在Python3.2中增强了zipfile.ZipExtFile(参见release notes).这些变化似乎使zipfile.ZipExtFileio.TextWrapper配合得很好.

顺便说一句,它在Python3.1中工作,如果您将下面的hacky行取消注释到monkey patch zipfile.ZipExtFile,我并不推荐这种黑客行为.我加入它只是为了说明在Python 3.2中为使事情顺利进行所做的工作的本质.

$ cat test_zip_file_py3k.py 
import csv, io, sys, zipfile

zip_file    = zipfile.ZipFile(sys.argv[1])
items_file  = zip_file.open('items.csv', 'rU')
# items_file.readable = lambda: True
# items_file.writable = lambda: False
# items_file.seekable = lambda: False
# items_file.read1 = items_file.read
items_file  = io.TextIOWrapper(items_file)

for idx, row in enumerate(csv.DictReader(items_file)):
    print('Processing row {0} -- row = {1}'.format(idx, row))

如果我必须支持py3k<;3.2,然后我会 Select my other answer的解决方案.

Python-3.x相关问答推荐

字符串块数组:如何根据一个数组中的元素对另一个数组中的元素进行分组

Numpy argmin()以查找最近的元组

无法使用Python slack 螺栓SDK读取在 slack 通道中收到的消息

使用递归将int转换为字符串

正确的本地react 方式-Django身份验证

根据另一列中的条件填写该列中的值

逐行比较2个Pandas数据帧,并对每一行执行计算

使用Python抓取sofascore以获取有关球队阵容和投票的信息

Python中根据分组/ID对两个数据框进行映射,以更接近值的升序排列

TypeError: issubclass() arg 1 在 Flask 中导入 langchain 时必须是一个类

类不继承时 super() 的用途

python2和python3中的列表生成器

Await Future 来自 Executor:Future 不能在await表达式中使用

判断对 python 3 支持的要求

如何判断一个字符串是否包含有效的 Python 代码

是否有与 Laravel 4 等效的 python?

所有 Python dunder 方法的列表 - 您需要实现哪些方法才能正确代理对象?

带百分号的 Python 字符串格式

是否在未完成初始化的对象上调用了 del?

为现有项目创建virtualenv