Using Python `namedtuple` objects to handle CSV rows
name,department,birthday month
John Smith,Accounting,November
Erica Meyers,IT,March
import csv
from collections import namedtuple
if __name__ == "__main__":
with open('input.csv') as csv_file:
csv_reader = csv.reader(csv_file)
# Row = namedtuple("Row", [x.replace(" ", "_") for x in next(csv_reader)])
Row = namedtuple("Row", ["name", "department", "birthday_month"])
for idx, row_data in enumerate(csv_reader):
row = Row(*row_data)
print(f'\t{row.name} works in the {row.department} department, and was born in {row.birthday_month}.')
Comments
Just a thought:
Given that namedtuple
type objects are
- Immutable
- Uses less memory and are faster
- Can be accessed with dot notation
- Can be subclassed to add functionality
- Can be typed
- ...are awesome
Aren't they the perfect option for processing CSV files? You could be lazy, not specify the headers, and it will work (just give you lint issues), or hardcode your row names and get the full experience.
What do you think?
Here is what it looks like when you do not hardcode the headers: