Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define column headers when reading a csv file in Python

Tags:

python

csv

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!

like image 451
myClone Avatar asked Nov 28 '22 18:11

myClone


1 Answers

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).

like image 103
David Z Avatar answered Dec 10 '22 12:12

David Z