CSV Files with the csv Module
This is a free course. Log in to run the code exercises and track your progress.
CSV Files with the csv Module
A CSV (comma-separated values) file is a text file in which every line is a record and commas separate its fields. The csv module reads and writes them correctly, including fields that themselves contain a comma (those are put in quotes).
import csv
with open("marks.csv", "w", newline="") as f:
w = csv.writer(f)
w.writerow(["Roll", "Name", "Marks"]) # one record
w.writerows([[1, "Asha", 88], [2, "Ravi", 72]]) # many records
with open("marks.csv", newline="") as f:
for row in csv.reader(f):
print(row) # ['Roll', 'Name', 'Marks'], ['1', 'Asha', '88'], ...
- Open CSV files with
newline="". Otherwise the writer's own line endings get an extra blank line on Windows. csv.readergives each record as a list of strings: convert numbers withint().- The first row is often a header; skip it with
next(reader). csv.writer(f, delimiter="|")uses another separator.
The input is a CSV file with a header row Roll,Name,Marks. Using csv.reader, skip the header and print the name of every student with marks above 75, then a last line Average: with the mean marks of all students to one decimal.
import csv
import sys
reader = csv.reader(sys.stdin) # stands in for csv.reader(open("marks.csv", newline=""))
marks = []
for row in reader:
pass # skip the header; collect the marks; print names above 75
print(f"Average: {sum(marks) / max(len(marks), 1):.1f}")Log in to edit and run this code.