0

我正在尝试使用 python 进行简单的 csv 解析,我有以下代码:

print csvdata
print "\n"
csvparsed = csv.reader(csvdata)

for row in csvparsed:
    print row

但是,似乎解析数据的每一行都是一个字符,并且没有用逗号分隔。我在这里错过了什么吗?这是我得到的输出:

Restaurant ID,2,,
,,,
Menu Name,Breakfast Menu,,

['R']
['e']
['s']
['t']
['a']
['u']
['r']
['a']
['n']
['t']
[' ']
['I']
['D']
['', '']
['2']
['', '']
['', '']
[]
['', '']
['', '']
['', '']
[]
['M']
['e']
['n']
['u']
[' ']
['N']
['a']
['m']
['e']
['', '']
['B']
['r']
['e']
['a']
['k']
['f']
['a']
['s']
['t']
[' ']
['M']
['e']
['n']
['u']
['', '']
['', '']
4

2 回答 2

4

csv.reader旨在为文本行提供迭代器,这就是打开文件的工作方式。你给了它一个字符串,当你迭代它时会产生字符。如果您从文件中获取数据,只需将打开的文件提供给csv.reader,不要先阅读文本。

如果您确实已经在字符串中包含文本,请使用以下命令:

csv.reader(csvdata.splitlines())
于 2012-06-03T01:24:09.790 回答
0

这可能更接近你想要做的事情:

csvparsed = csv.reader(open('csvdata', 'r'))

for row in csvparsed:
    print row

有了这个,以及您在文件中的示例数据,我得到了这个输出:

['Restaurant ID', '2', '', '']
['', '', '', '']
['Menu Name', 'Breakfast Menu', '', '']
于 2012-06-03T01:36:25.963 回答