CSV应返回字符串,而不是字节错误 [英] CSV Should Return Strings, Not Bytes Error
问题描述
我正在尝试从与我的Python脚本不在同一目录中的目录中读取CSV文件。
I am trying to read CSV files from a directory that is not in the same directory as my Python script.
此外,CSV文件存储在具有完全相同名称的ZIP文件夹中(唯一的区别是一个以.zip结尾,另一个以.csv结尾)。
Additionally the CSV files are stored in ZIP folders that have the exact same names (the only difference being one ends with .zip and the other is a .csv).
目前我使用Python的 zipfile
和 csv
打开并从文件获取数据,但是我得到的错误:
Currently I am using Python's zipfile
and csv
libraries to open and get the data from the files, however I am getting the error:
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])
如何解决此错误?
推荐答案
我肯定有一个更好的方法(只是偶然发现我现在)。如果您没有嵌入的新行,那么您可以使用:
It's a bit of a kludge and I'm sure there's a better way (that just happens to elude me right now). If you don't have embedded new lines, then you can use:
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)
这篇关于CSV应返回字符串,而不是字节错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!