用PythonparsingCSV文件

我有一个CSV文件,大约有30个标题(列)和2000行。

HeaderOne | HeaderTwo | HeaderThree dataRowOne | dataRowOne | dataRowOne dataRowTwo | dataRowTwo | dataRowTwo 

我想用Python来search一个string,然后输出该行。 所以说例如我search'cocaColaIsTheBest',它是在单元格E2018,我想Python打印出2018行上面的标题。

到目前为止,我有:

 import csv myExSpreadSheet = csv.reader(open('Simon.csv', 'rb')) for row in myExSpreadSheet: if 'cocaColaIsTheBest' in row: print (row) 

这将打印字典中的行; 我也想要它打印标题。

我怎样才能打印所有的标题?

我怎样才能打印特定的标题?

标题是第一行; 首先抓住那些人:

 with open('Simon.csv', 'rb') as csvfile: myExSpreadSheet = csv.reader(csvfile) headers = next(myExSpreadSheet, None) # grab first row for row in myExSpreadSheet: if 'cocaColaIsTheBest' in row: print headers print row 

你确定你没有使用DictReader更好吗? 然后,标题与相应的单元格相关联,您可以根据自己的喜好进行格式设置。