在Python中解析CSV文件

时间:2013-12-31 15:55:02

标签: python excel csv

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

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

我想使用Python搜索字符串,然后输出该行。所以说例如我搜索'cocaColaIsTheBest'并且它在单元格E2018中,我希望Python打印出2018行,上面有标题。

到目前为止,我已经:

import csv

myExSpreadSheet = csv.reader(open('Simon.csv', 'rb'))

for row in myExSpreadSheet:
    if 'cocaColaIsTheBest' in row:
        print (row)

这会在字典中打印行;我希望它也能打印标题。

如何打印所有标题?

如何打印特定标题?

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:2)

您确定使用DictReader并不是更好吗?然后标题与其相应的单元格相关联,您可以根据自己的喜好进行格式化。

相关问题