Using for loop to split CSV data and print one variable. ValueError: need more that 1 value to unpack?

Using for loop to split CSV data and print one variable. ValueError: need more that 1 value to unpack?

我正在尝试逐行读取 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)

控制台返回错误:

Traceback (most recent call last):
File "", line 1, in
File "C:\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 682, in runfile execfile(filename, namespace)
File "C:\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 85, in execfile exec(compile(open(filename, 'rb').read(), filename, 'exec'), namespace)
File "C:/Users/Nutrade/Desktop/Python/Quandl Hog Project/spreadmaker.py", line 6, in (d, o, h, l, la, ch, s, v, o) = line.split(",")
ValueError: need more than 1 value to unpack

有人可以解释为什么会这样以及如何纠正吗?

尝试分配给一个临时文件,如果长度不正确,则在尝试解包之前跳过。

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)

您的代码运行良好。正如 here, you probably have one or more blank lines at the end of your CSV file. (It's hard to tell from your question because the CSV file is not formatted nicely. Please refer here 所讨论的有关使用 Markdown 格式化文本的帮助。)