Read CSV with csv Module
Parse a CSV file using Python's csv module.
Code
Python
import csv
with open("data.csv", "r", encoding="utf-8") as f:
reader = csv.reader(f)
header = next(reader)
for row in reader:
print(dict(zip(header, row)))Line-by-line explanation
- 1.Import csv and open the file.
- 2.csv.reader() returns an iterator over rows.
- 3.next(reader) gets the header row.
- 4.zip(header, row) pairs column names with values.
Expected output
{'name': 'John', 'age': '30'}