Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 542
Brad T Avatar asked Nov 28 '25 08:11

Brad T


1 Answers

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

like image 146
sookool99 Avatar answered Nov 29 '25 23:11

sookool99



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!