ValueError:要解压的值太多(预计2

时间:2016-03-08 21:00:56

标签: python python-3.x

即使我的文件只有两列并且我使用它们,我也会收到此错误。

这是我的代码:

f_in = open('State_Deaths.csv', 'rt')
state_deaths = []
for line in f_in:
    line = line.strip()
    print(line)
    state, deaths = line.split(',')
    state_deaths += state, deaths
print(state_deaths)

这是文件的一部分:

state, deaths
Wyoming,155
Mississippi,641
Arkansas,563
Montana,189
Alabama,862
Oklahoma,668
Kentucky,760
South Carolina,810
South Dakota,140
West Virginia,315

1 个答案:

答案 0 :(得分:1)

我不知道你是否在列表列表或元组列表之后,所以这里有一些你可能不需要的额外输入检查。

state_deaths_lists = []
state_deaths_tuples = []

with open('State_Deaths.csv', 'r') as f:
    for line in f:
        line = line.strip()
        if "," not in line:
            print("Error - No comma found")
        else:
            row_vals = line.split(",")
            if len(row_vals) != 2:
                print("Error - More than 2 elements in line/row")
            else:
                # all's in order
                state_deaths_lists.append(row_vals)
                state_deaths_tuples.append(tuple(row_vals))

如果你的输入格式很好并且你想要一个列表列表,那就用这个:

state_deaths = []

with open('State_Deaths.csv', 'r') as f:
    for line in f:
        line = line.strip()
        row_vals = line.split(",")
        state_deaths.append(row_vals)