[英]Python reading csv file with semicolon delimiter: too many values to unpack
I am trying to read a csv file exported from Microsoft Excel, looking like this: 我正在尝试读取从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;;
The delimiter is semicolon and some of the columns might be empty. 定界符为分号,某些列可能为空。 For example column 10 may be populated with
asdasdf
as an example. 例如,列10可以填充
asdasdf
作为示例。 My code looks like this: 我的代码如下所示:
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)
I am getting the error ValueError: too many values to unpack
. 我收到错误
ValueError: too many values to unpack
。 What am I doing wrong here? 我在这里做错了什么?
There are 10 semicolons in each line of your CSV file, which means, that the line will be splitted into 11 elements. CSV文件的每一行中有10个分号,这意味着该行将被分成11个元素。 In your
for
loop, there are only 10 variables used. 在您的
for
循环中,仅使用了10个变量。 Change the line into: 将行更改为:
for x, y, z, safe, mod, descr_node, name, start, end, descr_path, _ in reader:
and ignore the _
variable, which will get the empty character between the last ;
并忽略
_
变量,该变量将在最后一个变量之间获取空字符;
in the line and the end of line. 在行和行尾。
Or change your whole loop into: 或将整个循环更改为:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.