tags:

views:

128

answers:

2

I have a comma separated value table that I want to read in Python. What I need to do is first tell Python not to skip the first row because that contains the headers. Then I need to tell it to read in the data as a list and not a string because I need to build an array out of the data and the first column is non-integer (row headers).

There are a total of 11 columns and 5 rows.
Here is the format of the table (except there are no row spaces):

col1,col2,col3,col4,col5,col6,col7,col8,col9,col10,col11

w0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
w1 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
w2 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
w3 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

Is there a way to do this? Any help is greatly appreciated!

+2  A: 

You can use the csv module for this sort of thing. It will read in each row as a list of strings representing the different fields.

How exactly you'd want to use it depends on how you're going to process the data afterwards, but you might consider making a Reader object (from the csv.reader() function), calling next() on it once to get the first row, i.e. the headers, and then iterating over the remaining lines in a for loop.

r = csv.reader(...)
headers = r.next()
for fields in r:
    # do stuff

If you're going to wind up putting the fields into a dict, you'd use DictReader instead (and that class will automatically take the field names from the first row, so you can just construct it an use it in a loop).

David Zaslavsky
Thanks David--this is what I am after!
myClone
A: 

Have you looked at the python csv module? It's the first thing I found on google and it even has examples at the bottom of the page.

hlfrk414