如果列具有特定值,则检索列标题

时间:2016-09-23 21:28:37

标签: python python-3.x csv

我有一个带有标题的csv文件,格式如下:

column1column2column3

TrueFalseFalse

FalseTrueTrue

在python中,如果值Truecolumn1之下,我想打印列名,然后是下一行column2column3) 。在下面的代码中,它会打印每一列。

    with open(reportOut, 'r') as f:
        reader = csv.reader(f, skipinitialspace=True)
        header = next(reader)
        for row in reader:
            if 'True' in row:
                print(header)

1 个答案:

答案 0 :(得分:1)

这有效:

import csv

with open("my.csv", 'r') as f:
    reader = csv.reader(f, skipinitialspace=True)
    headers = next(reader)
    # Start counting from 2 (Row #1 is headers)
    for row_number, row in enumerate(reader, 2):
        for column, val in enumerate(row):  # On each column in the row
            if val == "True":  # Check for the value
                # Print the header according to the column number
                print(row_number, headers[column])

输出:

2 column1
3 column2
3 column3