Python Program to Read a CSV File
Beginner · File handling
A CSV (comma separated values) file stores a table as plain text, one row per line with commas between the values, and spreadsheet programs like Excel can open it. This program creates a small CSV file of student marks, reads it with Python's csv module, and prints each row along with the class average.
Program
Columns: ['name', 'maths', 'science'] Aarav: maths 88, science 92 Diya: maths 95, science 89 Kabir: maths 76, science 81 Class average in maths: 86.3
How it works
- The sample file is written as plain text, so you can see exactly what a CSV file looks like: a header line, then one line per student.
csv.reader(f)turns each line into a list of values, split at the commas.next(reader)takes the first row, the column names, so the loop only sees the student rows.- Everything read from a CSV file is a string, so
int(row[1])turns the marks into numbers before they are added. - The csv module also copes with values that contain commas themselves, wrapped in quotes, which a plain
line.split(",")gets wrong.
Other ways to write it
Using csv.DictReader
Aarav scored 180 out of 200 Diya scored 184 out of 200 Kabir scored 157 out of 200
DictReader uses the header row as the keys, so row["maths"] names the column instead of relying on its position in the row.
Without the csv module
Aarav - maths: 88 science: 92 Diya - maths: 95 science: 89
Splitting each line at the commas works for simple files like this one, but breaks as soon as a value contains a comma, such as "Sharma, Riya", so the csv module is the safer choice.
Try it yourself
Add a fourth student to the sample file and also print the class average in science.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
- Write a CSV File
- Store and Search User IDs and Passwords in a CSV File
- Read and Write a JSON File
- Read a File Line by Line
- Read a Text File and Separate Words with #
- Count Vowels, Consonants, Uppercase and Lowercase Characters in a Text File
- Copy Lines Without the Letter 'a' to Another File
- Search a Roll Number in a Binary File
- Update Marks in a Binary File
- Count the Words "Me" and "My" in a Text File
All Python programs · CBSE class 12 practical file · Python exercises