0

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?

2
  • 1
    What do you mean "header of each row?" Was that a typo or you do have multiple header rows? Either way, if you want to grab the header, which presumably is the first non-blank row, then just pre-read the row and store it into a "header" buffer before you do your string search. If it's not the first row, then do a string search for the header row, then a string search for the data row. Commented Dec 31, 2013 at 15:57
  • Sorry, that was a typo. Just the header. Thanks Bill. Martijn's answer seems to do the trick, which is pretty much what you said. Cheers. Commented Dec 31, 2013 at 16:03

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Martijn. I owe you a pint! That works perfectly. What does the 'None' do in the headers = next line?
@BubbleMonster: It is the default value to return if the iterable is empty (if the file is empty, for example). It prevents a StopIteration exception from being raised, basically.
2

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.

1 Comment

This is especially useful if you only want certain column labels, or if the column layout might change.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.