【发布时间】:2016-05-01 20:06:19
【问题描述】:
我正在尝试从与我的 Python 脚本不同的目录中读取 CSV 文件。
此外,CSV 文件存储在具有完全相同名称的 ZIP 文件夹中(唯一的区别是一个以 .zip 结尾,另一个是以 .csv 结尾)。
目前我正在使用 Python 的 zipfile 和 csv 库来打开并从文件中获取数据,但是我收到了错误:
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])
我该如何解决这个错误?
【问题讨论】:
-
您是否在文本编辑器中打开文件以确保内容与您预期的一样?
-
是的,它们相当大,但仍然是标准的 csv、逗号分隔符等等。
-
发布错误的完整回溯可能会对您有所帮助。
-
好的,我更新了我的帖子。
-
改为这样打开:
with zipArchive.open(file[:-4] + '.csv', 'rt') as csvFile:
标签: python python-3.x csv zipfile