Python Code to Read and Write a CSV File
A CSV (comma separated values) file stores table data as plain text, one row per line. It can be opened in Excel, and Python has a built-in csv module to work with it.
Read a CSV file
Suppose we have a file named students.csv with this content:
name,marks
Robin,85
Maria,92
John,78
DictReader reads every row as a dictionary, using the first line as the keys.
import csv
total = 0
count = 0
with open("students.csv", newline="") as f:
reader = csv.DictReader(f)
for row in reader:
print(row["name"], row["marks"])
total += int(row["marks"])
count += 1
print("Average:", total / count)
Output:
Tutorials Class - Output Window
Robin 85
Maria 92
John 78
Average: 85.0
Values from a CSV file are always strings, so we used int() for the marks.
Write a CSV file
import csv
rows = [
["name", "marks"],
["Robin", 85],
["Maria", 92],
]
with open("result.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerows(rows)
print("File saved")
Output:
Tutorials Class - Output Window
File saved
The new file result.csv will have this content:
name,marks
Robin,85
Maria,92
Note:
Always open CSV files with newline="". It stops extra blank lines on Windows. Using with closes the file automatically, see the with statement.
Related: Python File Handling.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |