0

Consider a .csv file with the following format:

John,29,21,,DF,
Sara,23,51,,DF,
John,34,27,,ER,
John,76,29,,TY,
Sara,87,93,,SAD,

I need to retrieve the value in the second column for all the rows which have 'John' written in the first column. I want to do it using a python script. I'm very new to python so I'm asking how can this be done?

3
  • Take a look at the csv module. Commented Feb 15, 2014 at 16:00
  • Are there really spaces after the commas in your input CSV file? Commented Feb 15, 2014 at 16:02
  • @MartijnPieters, you're right, there are no spaces. I edited the question. Commented Feb 15, 2014 at 16:06

1 Answer 1

1

The csv module makes this trivial:

import csv

with open(inputfilename, 'rb') as infh:
    reader = csv.reader(infh)
    for row in reader:
        if row[0] == 'John':
            print row[1]

This assumes that you are using Python 2. The Python 3 version looks like:

import csv

with open(inputfilename, newline='') as infh:
    reader = csv.reader(infh)
    for row in reader:
        if row[0] == 'John':
            print(row[1])
Sign up to request clarification or add additional context in comments.

Comments

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.