繁体   English   中英

用Python解析CSV文件

[英]Parsing CSV files in Python

我有一个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)

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

如何打印所有标题?

以及如何打印特定的标题?

标头是第一行; 首先捕获那些:

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更好吗? 然后,标题与它们相应的单元格相关联,并且可以根据需要设置格式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM