我正在尝试阅读从Microsoft Excel导出的csv文件,如下所示:
114.9;280.9;501.5;0;W10;Firewall south;A;1;2;;
119.0;280.9;501.5;0;W10;Southern escape route;B;2;3;asdasdf;
120.5;280.0;501.5;0;W10;Southern escape route;C;3;4;;
分隔符是分号,有些列可能是空的。例如,可以用asdasdf
填充列10作为示例。我的代码如下所示:
reader = csv.reader(open(inFile), delimiter=";")
nodesTable = window.getNodesTable()
pathsTable = window.getPathsTable()
clearTable(nodesTable)
clearTable(pathsTable)
for x, y, z, safe, mod, descr_node, name, start, end, descr_path in reader:
nodesTable.SetStringItem(counter, nodesTable_ID_x, x)
nodesTable.SetStringItem(counter, nodesTable_ID_y, y)
nodesTable.SetStringItem(counter, nodesTable_ID_z, z)
nodesTable.SetStringItem(counter, nodesTable_ID_SafeArea, safe)
nodesTable.SetStringItem(counter, nodesTable_ID_Module, mod)
nodesTable.SetStringItem(counter, nodesTable_ID_Description, descr_node)
pathsTable.SetStringItem(counter, pathsTable_ID_Name, name)
pathsTable.SetStringItem(counter, pathsTable_ID_StartNode, start)
pathsTable.SetStringItem(counter, pathsTable_ID_EndNode, end)
pathsTable.SetStringItem(counter, pathsTable_ID_Description, descr_path)
我收到错误ValueError: too many values to unpack
。我在这里做错了什么?
答案 0 :(得分:5)
您的CSV文件的每一行都有 10 分号,这意味着该行将被拆分为 11 元素。在for
循环中,只使用 10 变量。将行更改为:
for x, y, z, safe, mod, descr_node, name, start, end, descr_path, _ in reader:
并忽略_
变量,该变量将在行中的最后;
和行尾之间获得空字符。
或者将整个循环改为:
cols = (nodesTable_ID_x, nodesTable_ID_y, nodesTable_ID_z,
nodesTable_ID_SafeArea, nodesTable_ID_Module,
nodesTable_ID_Description, pathsTable_ID_Name,
pathsTable_ID_StartNode, pathsTable_ID_EndNode,
pathsTable_ID_Description)
for rec in reader:
for col, val in zip(cols, rec):
nodesTable.SetStringItem(counter, col, val)