Brad T
Brad T

Reputation: 1617

How can I read a CSV file line by line while keeping track of the column headers?

When using this code:

with open(filepath, 'r') as f:
    reader = csv.reader(f)
    for i, line in enumerate(reader):
        print 'line[{}] = {}'.format(i, line)

It reads my CSV files line by line, but I can't select the line I want by its header. The index will probably change from file to file, so I feel this wouldn't be a good way to select the column I want in a row. What's a good way to approach this?

Upvotes: 3

Views: 6468

Answers (1)

sookool99
sookool99

Reputation: 262

From the csv documentation, use DictReader instead of just reader. Updating your implementation to:

import csv
with open(filename, 'r') as f:
    reader = csv.DictReader(f)
    for i, line in enumerate(reader):
        print 'line[{}] = {}'.format(i, line['header_name'])

Documentation on DictReader found here: https://docs.python.org/2/library/csv.html#csv.DictReader

Upvotes: 3

Related Questions