0

I am trying to do a simple csv parsing using python, I have the following code:

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']
['', '']
['', '']

2 Answers 2

4

csv.reader is meant to be given an iterator over lines of text, which is how an open file works. 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.

If you really do already have the text in a string, then use this:

csv.reader(csvdata.splitlines())
Sign up to request clarification or add additional context in comments.

Comments

0

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', '', '']

1 Comment

my problem was that the data is already in the form of a string and not in a file

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.