Reputation: 1416
I have a CSV file that has around 30 headers (columns) and 2000 rows.
HeaderOne | HeaderTwo | HeaderThree
dataRowOne | dataRowOne | dataRowOne
dataRowTwo | dataRowTwo | dataRowTwo
I want to use Python to search for a string, then output that row. 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.
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?
Upvotes: 0
Views: 154
Reputation: 391
Are you sure you're not better off using a DictReader? Then the headings are associated with their corresponding cells and you can format however you like.
Upvotes: 2
Reputation: 1125368
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
Upvotes: 3