[英]Parsing CSV files in Python
I have a CSV file that has around 30 headers (columns) and 2000 rows. 我有一个CSV文件,包含大约30个标题(列)和2000行。
HeaderOne | HeaderTwo | HeaderThree
dataRowOne | dataRowOne | dataRowOne
dataRowTwo | dataRowTwo | dataRowTwo
I want to use Python to search for a string, then output that row. 我想使用Python搜索字符串,然后输出该行。 So say for example I search for 'cocaColaIsTheBest' and it is in cell E2018, I want Python to print out row 2018 with the headers above it. 举例来说,例如我搜索了'cocaColaIsTheBest',它在单元格E2018中,我希望Python打印出2018年行,其标题位于其上方。
So far, i've got: 到目前为止,我已经:
import csv
myExSpreadSheet = csv.reader(open('Simon.csv', 'rb'))
for row in myExSpreadSheet:
if 'cocaColaIsTheBest' in row:
print (row)
This prints the row in a dictionary; 这将在字典中打印该行; I want it to print the header as well. 我也希望它打印标题。
How can I print all headers? 如何打印所有标题?
And how can I print specific headers? 以及如何打印特定的标题?
The headers are the first row; 标头是第一行; capture those first: 首先捕获那些:
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
Are you sure you're not better off using a DictReader ? 您确定使用DictReader更好吗? Then the headings are associated with their corresponding cells and you can format however you like. 然后,标题与它们相应的单元格相关联,并且可以根据需要设置格式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.