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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With