CSV files, board style
Part of the free LogicWiz Python course, Pack A: CBSE Class 12 Board Pack. The examples and practice run in the app.
Raj runs a medical store and keeps sales in Sales.csv. On his Windows PC every row was followed by a blank row, and his total crashed with ValueError. Two small things fix it: newline="" and next().
You'll learn to
- Write rows with csv.writer(), writerow() and writerows(), using newline=""
- Read rows with csv.reader() and convert the strings to numbers
- Solve the board's Accept()/Total() and user-id/password programs
Learn
CSV in four calls
A CSV (comma-separated values) file is plain text: one record per line, fields separated by commas. Excel opens it as a table.
w = csv.writer(f)makes a writer for an open file.w.writerow(list)writes one row.w.writerows(list_of_lists)writes many rows.csv.reader(f)gives each row back as a list of strings.
Open CSV files with newline="", for writing and reading.
Write a table, read it back
import csv
rows = [["P01", "Paracetamol", 10, 25.5], ["P02", "Cough syrup", 2, 90]]
with open("Sales.csv", "w", newline="") as f:
w = csv.writer(f)
w.writerow(["Product_ID", "Product_Name", "Quantity_Sold", "Price_Per_Unit"])
w.writerows(rows)
with open("Sales.csv", "r", newline="") as f:
for row in csv.reader(f):
print(row)
Look at the output: 10 came back as '10'. Everything a reader gives you is a string.
Two classic CSV mistakes.
- Forgetting
newline="". The writer already ends each row with\r\n; on Windows, text mode adds another\r, so you see a blank line after every row. - Doing maths on strings.
row[2] + row[3]joins text. Convert first:int(row[2]) * float(row[3]).
writerow vs writerows
| w.writerow(row) | w.writerows(rows) |
|---|---|
| Writes one row | Writes many rows |
| Argument: a list like ["P03", "Dettol", 1, 120] | Argument: a list of lists |
| Use inside a loop or for the header | Use when you already have all rows |
Board pattern: Accept() and a total
import csv
def Accept():
pid = input("Product ID: ")
name = input("Product name: ")
qty = int(input("Quantity sold: "))
price = float(input("Price per unit: "))
with open("Sales.csv", "a", newline="") as f: # a = add, keep old rows
csv.writer(f).writerow([pid, name, qty, price])
def CalculateTotalSales():
total = 0
with open("Sales.csv", "r", newline="") as f:
r = csv.reader(f)
next(r) # skip the header row
for row in r:
total += int(row[2]) * float(row[3])
return total
Accept()
print()
print("Total sales: Rs", CalculateTotalSales())
next(r) reads one row and throws it away. Without it, int("Quantity_Sold") raises ValueError.
Practical-list program: user-id and password
import csv
with open("users.csv", "w", newline="") as f:
csv.writer(f).writerows([["aarav12", "chai@123"], ["meher07", "samosa#9"], ["riya", "metro2025"]])
def find_password(uid):
with open("users.csv", "r", newline="") as f:
for row in csv.reader(f):
if row[0] == uid:
return row[1]
return None
uid = input("User id: ")
pw = find_password(uid)
if pw is None:
print("User id not found")
else:
print("Password:", pw)
This exact task (create a CSV of user-ids and passwords, then search) is on the CBSE suggested practical list.
4-mark CSV question: one function adds a record typed by the user, the other reads the file and computes something. Marks for: import csv · open(..., "a", newline="") · writer() + writerow() · reader() · skipping the header · converting with int()/float() · return. Use "a" in Accept(); "w" would wipe earlier sales.
In one line
Open CSV files with newline=""; writerow/writerows write, reader reads lists of strings; skip the header with next() and convert before maths.