Created
October 2, 2022 08:56
-
-
Save avi-perl/a79be4242d7bf54de09d28850fd74198 to your computer and use it in GitHub Desktop.
Using Python `namedtuple` objects to handle CSV rows
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
name | department | birthday month | |
---|---|---|---|
John Smith | Accounting | November | |
Erica Meyers | IT | March |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}.') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just a thought:
Given that
namedtuple
type objects areAren'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: