[英]python csv not parsing delimiter
I am trying to do a simple csv parsing using python, I have the following code: 我正在尝试使用python做一个简单的csv解析,我有以下代码:
print csvdata
print "\n"
csvparsed = csv.reader(csvdata)
for row in csvparsed:
print row
However, it seems that each row of the parsed data is a single character and not separated by the commas. 但是,似乎解析的数据的每一行都是单个字符,并且没有用逗号分隔。 Am I missing something here?
我在这里想念什么吗? This is the output I'm getting:
这是我得到的输出:
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']
['', '']
['', '']
csv.reader
is meant to be given an iterator over lines of text, which is how an open file works. csv.reader
为csv.reader
提供一个在文本行上进行迭代的迭代器,这是打开文件的工作方式。 You gave it a string, which produces characters when you iterate it. 您给它提供了一个字符串,该字符串在您进行迭代时会产生字符。 If you are getting the data from a file, simply give the open file to
csv.reader
, don't read the text first. 如果要从文件获取数据,只需将打开的文件提供给
csv.reader
,不要先阅读文本。
If you really do already have the text in a string, then use this: 如果您确实已经在字符串中包含了文本,请使用以下命令:
csv.reader(csvdata.splitlines())
This might be closer to what you're trying to do: 这可能更接近您要执行的操作:
csvparsed = csv.reader(open('csvdata', 'r'))
for row in csvparsed:
print row
With this, and your sample data in a file, I get this output: 有了这个,以及您的示例数据在文件中,我得到以下输出:
['Restaurant ID', '2', '', '']
['', '', '', '']
['Menu Name', 'Breakfast Menu', '', '']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.