Reading CSV files in Python

Assume you have a CSV file named data.csv with this content:

name,age,city
Alice,20,Toronto
Bob,22,Montreal
Charlie,25,Vancouver

1) Read Entire CSV

Read data.csv and print each row as a list.


2) Skip Header

Read data.csv and print only data rows (skip the header).


3) Print First Column

Read data.csv and print only the name column.


4) Print Second Column

Read data.csv and print only the age column.


5) Print Third Column

Read data.csv and print only the city column.


6) Count Rows

Read data.csv and print how many data rows (excluding header) it has.


7) Print Ages as Integers

Read ages from data.csv, convert to int, and print.


8) List of Names

Read data.csv and save all names into a list, then print the list.


9) Names Above Certain Age

Read data.csv and print names of people older than 21.


10) Print in Formatted Lines

Display each row like:


11) Read Using DictReader

Read data.csv using csv.DictReader and print each row as a dictionary.


12) Print Names Using DictReader

Use csv.DictReader and print only the name value from each row.


13) Print Age + City Together

Use DictReader and combine fields:


14) Sum of Ages

Read all ages from the CSV and print their total.


15) Average Age

Read ages and print the average age.


16) Unique Cities

Read the file and print a list of unique cities (no duplicates).


17) Search Name

Ask user for a name and print the corresponding row if found.


18) Save Ages to List

Extract the age column into a list of integers and print it.


19) Count by City

Read data.csv and count how many people are from each city.

Expected output example:


20) Print All Rows Reverse Order

Read all rows (excluding header) and print them in reverse order.


πŸ”Ž Useful Code Snippets

Basic Reader

DictReader


πŸ“Œ Notes for Students

🟒 Use csv.reader when you want each row as a list. 🟑 Use csv.DictReader when you want each row as a dictionary with headers. πŸ”΅ Always skip the header when doing data-only tasks (unless using DictReader).


canvil: 333f6c7d-6876-4f7e-b6ad-1bdb2233f5c1

Last updated