开发者

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

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,开发者_Python百科 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!


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜