Read specific columns in csv using python

前端 未结 7 1367
耶瑟儿~
耶瑟儿~ 2021-02-06 06:27

I have a csv file that look like this:

+-----+-----+-----+-----+-----+-----+-----+-----+
| AAA | bbb | ccc | DDD | eee | FFF | GGG | hhh |
+-----+-----+-----+-----+---         


        
7条回答
  •  鱼传尺愫
    2021-02-06 06:57

    I realize the answer has been accepted, but if you really want to read specific named columns from a csv file, you should use a DictReader (if you're not using Pandas that is).

    import csv
    from StringIO import StringIO
    
    columns = 'AAA,DDD,FFF,GGG'.split(',')
    
    
    testdata ='''\
    AAA,bbb,ccc,DDD,eee,FFF,GGG,hhh
    1,2,3,4,50,3,20,4
    2,1,3,5,24,2,23,5
    4,1,3,6,34,1,22,5
    2,1,3,5,24,2,23,5
    2,1,3,5,24,2,23,5
    '''
    
    reader = csv.DictReader(StringIO(testdata))
    
    desired_cols = (tuple(row[col] for col in columns) for row in reader)
    

    Output:

    >>> list(desired_cols)
    [('1', '4', '3', '20'),
     ('2', '5', '2', '23'),
     ('4', '6', '1', '22'),
     ('2', '5', '2', '23'),
     ('2', '5', '2', '23')]
    

提交回复
热议问题