Python Pages Doc Ic Ac Uk CPP Lessons CPP 10 Files 09 Csvreaddict HTML
Python Pages Doc Ic Ac Uk CPP Lessons CPP 10 Files 09 Csvreaddict HTML
It might be a hassle to count the index of columns you want from a CSV, especially when there are too many
columns!
To make life easier, you can also read in the CSV files into a dict, using a csv.DictReader object. You can then
access elements using the column names as keys (from the first row). There is also no need to explicitly read the
header row (this is automatically done by csv.DictReader).
1 import csv
2
3 with open("students.csv") as csv_file:
4 reader = csv.DictReader(csv_file)
5
6 for row in reader:
7 print(f"Student {row['name']} is from the Faculty of {row['faculty']}, "
8 f"{row['department']} dept.")
If the CSV file does not contain a header row, you will need to specify your own keys. You can do this by
assigning the fieldnames argument with a list that contains your column names.
1 headers = ["name", "faculty", "department"]
2 reader = csv.DictReader(csv_file, fieldnames=headers)
Previous Next