2016-09-23 60 views
0

我有以下列格式与标头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

这工作:

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 
相关问题