Read specific columns in csv using python

前端 未结 7 1370
耶瑟儿~
耶瑟儿~ 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 07:00

    All other answers are good, but I think it would be better to not load all data at the same time because the csv file could be really huge. I suggest using a generator.

    def read_csv(f, cols):
        reader = csv.reader(f)
        for row in reader:
            if len(row) == 1:
                columns = row[0].split()
                yield (columns[c] for c in cols)
    

    Which can be used for a for loop after

    with open('path/to/test.csv', 'rb') as f:
        for bbb, ccc in read_csv(f, [1, 2]):
            print bbb, ccc
    

    Of course you can enhance this function to receive the column's name instead of the index. To do so, just mix Brad M answer and mine.

提交回复
热议问题