Subway
Subway

Reputation: 5716

python: extracting values from csv file by row name

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?

Upvotes: 0

Views: 7874

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121266

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])

Upvotes: 1

Related Questions