CSV 应该 Return 字符串,而不是字节错误

CSV Should Return Strings, Not Bytes Error

我正在尝试从与我的 Python 脚本不在同一目录中的目录中读取 CSV 文件。

此外,CSV 文件存储在名称完全相同的 ZIP 文件夹中(唯一的区别是一个以 .zip 结尾,另一个以 .csv 结尾)。

目前我正在使用 Python 的 zipfilecsv 库来打开文件并从中获取数据,但是我收到错误消息:

Traceback (most recent call last):   File "write_pricing_data.py", line 13, in <module>
    for row in reader:
_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)

我的代码:

import os, csv
from zipfile import *

folder = r'D:/MarketData/forex'
localFiles = os.listdir(folder)

for file in localFiles:
    zipArchive = ZipFile(folder + '/' + file)

    with zipArchive.open(file[:-4] + '.csv') as csvFile:
        reader = csv.reader(csvFile, delimiter=',')

        for row in reader:
            print(row[0])

我该如何解决这个错误?

这有点麻烦,我相信有更好的方法(我现在恰好不知道)。如果你没有嵌入新行,那么你可以使用:

import zipfile, csv

zf = zipfile.ZipFile('testing.csv.zip')
with zf.open('testing.csv', 'r') as fin:
    # Create a generator of decoded lines for input to csv.reader
    # (the csv module is only really happy with ASCII input anyway...)
    lines = (line.decode('ascii') for line in fin)
    for row in csv.reader(lines):
        print(row)