我试图逐行读取CSV数据,在每一行中分离出1条数据并打印出来。
来自CSV的样本:
Date,Open,High,Low,Last,Change,Settle,Volume,Prev. Day Open Interest
1969-06-25,22.0,22.0,22.0,,,22.0,3.0,3.0
1969-06-26,23.0,23.0,21.9,,,21.9,6.0,9.0我的代码:
file1 = 'LNG1970'
infile = open(('%s.csv' % file1), 'r')
for line in infile.readlines():
(d, o, h, l, la, ch, s, v, o) = line.split(",")
print(d)控制台中返回的错误:
回溯(最近一次调用): 文件"",第1行,在 文件"C:\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py",第682行,在runfile execfile中(文件名,命名空间) 文件"C:\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py",第85行,在execfile exec(编译(打开(文件名,'rb').read(),文件名,'exec'),命名空间) 在(d,o,h,l,la,ch,s,v,o) = line.split(",")中,文件“C:/User/Nutrade/Desktop/Python/Quandl Hog Project/spreadmaker.py",第6行 ValueError:需要超过一个值才能解包
有谁能解释一下为什么会发生这种情况,以及如何纠正?
发布于 2015-07-03 18:05:30
发布于 2015-07-03 18:04:55
如果长度不正确,请尝试将其赋值给临时包,然后在解压缩之前跳过。
for line in infile.readlines():
temp = line.split(",")
if not len(temp) == 9:
continue
(d, o, h, l, la, ch, s, v, o) = temp
print(d)https://stackoverflow.com/questions/31212027
复制相似问题