CSV Files: reader & writer
What is a CSV file?
CSV (Comma-Separated Values) is a plain-text file in which each line is a record and the values (fields) are separated by commas. Spreadsheets like Excel and Google Sheets open and save CSV, so it is the most common way to exchange table data.
| Roll | Name | Class | Marks |
|---|---|---|---|
| 1 | Asha | XII-A | 91 |
| 2 | Ravi | XII-B | 67 |
| 3 | Neha | XII-A | 85 |
Roll,Name,Class,Marks 1,Asha,XII-A,91 2,Ravi,XII-B,67 3,Neha,XII-A,85
The csv module
Writing: writer, writerow, writerows
import csv
rows = [['Roll', 'Name', 'Class', 'Marks'],
[1, 'Asha', 'XII-A', 91],
[2, 'Ravi', 'XII-B', 67],
[3, 'Neha', 'XII-A', 85]]
with open('result.csv', 'w', newline='') as f:
w = csv.writer(f)
w.writerow(rows[0]) # header
w.writerows(rows[1:]) # many rows at once
with open('result.csv') as f:
print(f.read(), end='') # it is just textWhy newline=''?
When opening a CSV file for writing, pass newline=''. Otherwise, on Windows, an empty line appears after every row because both Python and the csv module add line endings.
Reading with csv.reader
import csv
with open('result.csv', newline='') as f:
r = csv.reader(f)
for row in r:
print(row) # every row is a LIST of stringsAppending a row
import csv
def add_student():
with open('result.csv', 'a', newline='') as f:
csv.writer(f).writerow([4, 'Kabir', 'XII-B', 74])
add_student()
with open('result.csv', newline='') as f:
data = list(csv.reader(f))
print('Rows (with header):', len(data), '| last:', data[-1])Searching, counting and filtering
import csv
def toppers(limit):
with open('result.csv', newline='') as f:
r = csv.reader(f)
next(r) # skip the header row
count = 0
for roll, name, cls, marks in r:
if int(marks) > limit: # convert text to number
print(name, marks)
count += 1
print('Count:', count)
toppers(80)import csv
def search(name):
with open('result.csv', newline='') as f:
for row in csv.reader(f):
if row[1].lower() == name.lower():
return row
return None
print(search('neha'))
print(search('Zoya'))import csv
# copy only XII-B students into a new CSV
with open('result.csv', newline='') as src, open('xiib.csv', 'w', newline='') as dst:
r = csv.reader(src)
w = csv.writer(dst)
w.writerow(next(r)) # copy header
for row in r:
if row[2] == 'XII-B':
w.writerow(row)
with open('xiib.csv') as f:
print(f.read(), end='')DictReader
import csv
def class_average(section):
total = n = 0
with open('result.csv', newline='') as f:
for row in csv.DictReader(f): # each row is a dict
if row['Class'] == section:
total += int(row['Marks'])
n += 1
return round(total / n, 2) if n else 0
print('XII-A average:', class_average('XII-A'))
print('XII-B average:', class_average('XII-B'))Other delimiters
import csv
with open('items.csv', 'w', newline='') as f:
w = csv.writer(f, delimiter=';') # semicolon-separated
w.writerow(['Item', 'Price'])
w.writerow(['Pen, blue', 10]) # comma inside value is safe
with open('items.csv') as f:
print(f.read(), end='')
with open('items.csv', newline='') as f:
print(list(csv.reader(f, delimiter=';')))The csv module automatically puts quotes around a value that contains the delimiter, so "Pen, blue" stays one field.
Summary & practice
- CSV = text table, comma-separated; open with
newline=''. - Write with csv.writer → writerow / writerows; read with csv.reader (rows are lists of strings).
- Skip the header with
next(reader); convert numbers before maths.
Write ADD() to accept and add [EmpID, Name, Mobile] to record.csv, and COUNTR() to count the number of records in the file (without the header).
