1

I have a small issue while trying to parse some data from a table. My program reads a row of the table and then puts it in a list as a string (Python does this as default with a reader.next() function). Everything is fine until there aren't any commas separating some text on the same table space. In this case, the program thinks the comma is a separator and makes 2 list indexes instead of one, and this makes things like list[0].split(';') impossible.

I suck at explaining verbally, so let me illustrate:

csv_file = | House floors | Wooden, metal and golden | 2000 |   # Illustration of an excel table

reader = csv.reader(open('csv_file.csv', 'r'))
row = reader.next()  # row: ['House floors;Wooden', 'metal and golden; 2000']
columns = row.split(';')  # columns: ['House floors, Wooden', 'metal and golden', '2000']

# But obviously what i want is this:
# columns : ['House floors', 'Wooden, metal and golden', '2000']

Thank you very much for your help!

1
  • why are you splitting on ';' can you show some sample data? Commented Nov 15, 2012 at 19:29

2 Answers 2

5

set the delimiter http://docs.python.org/2/library/csv.html

csv.reader(fh, delimiter='|')
Sign up to request clarification or add additional context in comments.

3 Comments

The problem is not the delimiter, as my delimiter is ';', not a comma.
then set it to ; and the split by |. not clear from your example
Ok , this worked. Thank you! But may i ask you one more thing. Does the deliminter mean the seperator between columns? Because when i set the delimiter to '|', my python idle still prints the rows with a ';' between each column data.
0

You need to set correct delimiter which in your case would be | or ; (not clear from OP's example) e.g.

csv.reader(csvfile, delimiter=';')

Assuming you have data like "House floors;Wooden, metal and golden;2000" you can easily parse it using csv module

import csv
import StringIO
data = "House floors;Wooden, metal and golden;2000"

csvfile = StringIO.StringIO(data)

for row in csv.reader(csvfile, delimiter=';'):
    print row

output:

['House floors', 'Wooden, metal and golden', '2000']

Comments

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.