gpt4 book ai didi

Python 读取带分号分隔符的 csv 文件 : too many values to unpack

转载 作者:太空宇宙 更新时间:2023-11-04 09:11:15 25 4
gpt4 key购买 nike

我正在尝试读取从 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;;

分隔符为分号,部分列可能为空。例如,第 10 列可能会填充 asdasdf 作为示例。我的代码如下所示:

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。我在这里做错了什么?

最佳答案

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)

关于Python 读取带分号分隔符的 csv 文件 : too many values to unpack,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14877371/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com