0

我的 MacBook Air 上运行着 python。我有一个简单的示例,我正在尝试使用 Python 的漂亮表读取 csv:

from prettytable import from_csv`
fp = open("test.csv", "r")`
pt = from_csv(fp)`
fp.close()

下面是我的 csv“test.csv”:

name,city,areacode
joe,chicago,312
sam,san diego,619

当我运行代码时,我收到以下错误:

%> python3 prettytable-testing2.py 
Traceback (most recent call last):
File "prettytable-testing2.py", line 3, in <module>
pt = from_csv(fp)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/prettytable.py", line 1351, in from_csv
table.add_row([x.strip() for x in row])
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/prettytable.py", line 818, in add_row
raise Exception("Row has incorrect number of values, (actual) %d!=%d (expected)" %(len(row),len(self._field_names)))
Exception: Row has incorrect number of values, (actual) 0!=3 (expected)

很好奇为什么当显然有 3 个字段和 2 行带有数据的项目时,它会得到 0 值。

谢谢

4

1 回答 1

1

我试过你的代码,但我没有得到同样的错误。

我认为您可能在文件末尾或某处有一个空行。当我添加一个空行时,我得到了像你这样的错误:

Exception: Row has incorrect number of values, (actual) 0!=3 (expected)
于 2015-01-26T03:49:26.930 回答