2016-09-23 54 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 
相關問題