我不知道"Too many values to unpack" Exception如何适用于我的问题,如果有,请解释
回溯:
c:\***>python graphJSON.py
Traceback (most recent call last):
File "graphJSON.py", line 17, in <module>
for region, four, one, two, three, threep in rows:
ValueError: too many values to unpack
我遇到了太多的值错误这个简单的代码,无法弄清楚问题是什么:错误来自for循环。我已经收到一条消息,说之前有人问过这个问题,答案是完全不清楚的!
rows = csv.reader(open("graph.csv", "rb"))
# Init the the lists that will store our data
regions = []
fourHrs = []
oneDay = []
twoDay = []
threeDay = []
plusThreeDay = []
# Iterate through all the rows in our CSV
for region, four, one, two, three, threep in rows:
regions = regions + [region]
fourHrs = fourHrs + [four]
oneDay = oneDay + [one]
twoDay = twoDay + [two]
threeDay = threeDay + [three]
plusThreeDay = plusThreeDay + [threep]
# Format the output
output = {"data":[{"Regions":regions},
{"Four Hours":fourHrs},
{"One Day":oneDay},
{"Two Days":twoDay},
{"Three Days":threeDay},
{"More than Three Days":plusThreeDay}
]}
生成JSON文件 json_file = open(“graph.json”,“w”) json.dump(输出,json_file) csv中的数据如下所示:
First 28 25 10 2 7
Second 51 17 8 5 15
Third 38 33 24 7 19
回答:事实证明问题出在CSV上,它在我删除的一个阶段有更多列,但是,我认为在Excel中,引用不会被完全删除。所以,在从stratch重做CSV时它起作用了!
答案 0 :(得分:3)
首先,正如@Wooble指出的那样,你必须遍历csv文件中的每一行,而不是通过csv文件本身。
一旦完成,异常将由以下行引起:
for region, four, one, two, three, threep in rows:
您可以通过异常追溯确认。
问题的原因是rows
项目的项目数量少于您的代码将其设置为展开的目标项目:
region, four, one, two, three, threep
即。少于/超过6项。
答案 1 :(得分:0)
可能是因为您的CSV文件中有一行或多行包含少于6个字段。元组解包用于将从CSV文件迭代器返回的行解包到for循环标题中列出的六个变量名;错误对我来说很有意义!