我有一个带有标题的csv文件,格式如下:
column1
,column2
,column3
True
,False
,False
False
,True
,True
在python中,如果值True
在column1
之下,我想打印列名,然后是下一行column2
和column3
) 。在下面的代码中,它会打印每一列。
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)
答案 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