我正在尝试使用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']
['', '']
['', '']
答案 0 :(得分:4)
csv.reader
意味着在文本行上给出一个迭代器,这就是打开文件的工作方式。你给了它一个字符串,当你迭代它时会产生字符。如果您从文件中获取数据,只需将打开的文件提供给csv.reader
,不要先阅读文本。
如果你确实已经在字符串中包含了文本,那么请使用:
csv.reader(csvdata.splitlines())
答案 1 :(得分:0)
这可能更接近你想要做的事情:
csvparsed = csv.reader(open('csvdata', 'r'))
for row in csvparsed:
print row
有了这个,你的样本数据在一个文件中,我得到了这个输出:
['Restaurant ID', '2', '', '']
['', '', '', '']
['Menu Name', 'Breakfast Menu', '', '']