Courses / Computer Science XII (HSSC-II) – FBISE Complete SLO-Based Course
3.4 File Handling in Python: Writing, Reading and Counting Letters
Unit 3 – Programming Fundamentals · 90 min read · 8 MCQs to check yourself
Corey Schafer – file objects: reading and writing to files
1. Why disk I/O?
Variables live in RAM, which is volatile – everything is lost when the program ends or power goes. Disk I/O (input/output) lets programs save data permanently (marks, settings, logs, game progress) and read data created by others (CSV exports, text reports).
2. File operations
| Operation | Python | Notes |
|---|---|---|
| Open | f = open("marks.txt", "r") |
Returns a file object |
| Create / write | mode "w" |
Creates the file; overwrites if it exists |
| Append | mode "a" |
Adds to the end; creates if missing |
| Read | mode "r" (default) |
Error if the file does not exist |
| Create only | mode "x" |
Error if the file already exists |
| Close | f.close() |
Saves buffered data and frees the file |
| Safe open | with open(...) as f: |
Closes automatically, even after errors |
with open("marks.txt", "w") as f: # create and write
f.write("Ali,85\n")
f.write("Sara,91\n")
with open("marks.txt", "a") as f: # append
f.write("Bilal,72\n")
with open("marks.txt") as f: # read the whole file
print(f.read())
with open("marks.txt") as f: # read line by line
total = 0
for line in f:
name, mark = line.strip().split(",")
total += int(mark)
print("Average:", round(total / 3, 2))
Output:
Ali,85
Sara,91
Bilal,72
Average: 82.67
| Reading method | Returns |
|---|---|
f.read() |
the whole file as one string |
f.readline() |
the next line |
f.readlines() |
a list of all lines |
for line in f: |
one line at a time (memory-friendly for big files) |
3. Handling errors
try:
with open("missing_file.txt") as f:
print(f.read())
except FileNotFoundError:
print("File not found – please check the name.")
Output:
File not found – please check the name.
4. PBA program – count the occurrences of each letter
text = """Pakistan Zindabad!
Computer Science is fun."""
with open("story.txt", "w") as f: # create a sample file
f.write(text)
counts = {}
with open("story.txt") as f:
for ch in f.read().lower():
if ch.isalpha(): # letters only – ignore spaces, digits, punctuation
counts[ch] = counts.get(ch, 0) + 1
for letter in sorted(counts):
print(letter, counts[letter])
Output:
a 4
b 1
c 3
d 2
e 3
f 1
i 4
k 1
m 1
n 4
o 1
p 2
r 1
s 3
t 2
u 2
z 1
Debugging notes for this program: forgetting .lower() counts “P” and “p” separately; forgetting isalpha() counts spaces and “!”; using counts[ch] += 1 without a default raises KeyError the first time a letter appears – counts.get(ch, 0) avoids it.
5. CSV files
import csv
with open("students.csv", "w", newline="") as f:
w = csv.writer(f)
w.writerow(["roll", "name", "marks"])
w.writerows([[1, "Ali", 85], [2, "Sara", 91]])
with open("students.csv") as f:
for row in csv.DictReader(f):
print(row["name"], row["marks"])
Output:
Ali 85
Sara 91
Short and long questions
1. Write, execute and debug a Python program that reads a text file from disk and prints the number of occurrences of each letter of the alphabet. Explain how your program treats upper/lower case and non-letter characters, and mention two errors you might meet while debugging it. (4 + 2)
Model answer
counts = {}
try:
with open("story.txt", "r") as f:
text = f.read().lower() # treat 'A' and 'a' as the same letter
for ch in text:
if ch.isalpha(): # ignore spaces, digits, punctuation
counts[ch] = counts.get(ch, 0) + 1
for letter in sorted(counts):
print(letter, counts[letter])
except FileNotFoundError:
print("story.txt not found")
Explanation (4): the file is opened in read mode with with; the whole text is converted to lower case so capital and small letters are counted together; isalpha() skips spaces, numbers and symbols; a dictionary stores letter → count; get(ch, 0) gives 0 the first time a letter appears; the letters are printed in alphabetical order.
Debugging (2): (1) FileNotFoundError if the file name/path is wrong – handled by try/except; (2) KeyError if counts[ch] += 1 is used for a new letter – fixed with get(); (also: forgetting .lower() gives separate counts for “A” and “a”; forgetting isalpha() counts spaces.)
2. Why should files be opened with the with statement? How are missing files handled?
Model answer
with open(...) as f: automatically closes the file when the block ends, even if an error occurs, so data is saved and the file is released.
Missing files are handled with try/except FileNotFoundError, printing a friendly message instead of crashing.
3. Differentiate between "w" and "a" file modes with an example.
Model answer
- "w" (write): creates the file or erases its existing content and writes new data.
open("log.txt","w").write("A")→ file has only “A”. - "a" (append): keeps existing content and adds new data at the end. Then
open("log.txt","a").write("B")→ file has “AB”.
4. Write a Python program to create a file named "notes.txt", write three lines in it and then read and display the file.
Model answer
with open("notes.txt", "w") as f:
f.write("Line 1\n")
f.write("Line 2\n")
f.write("Line 3\n")
with open("notes.txt", "r") as f:
print(f.read())
5. What is the importance of disk I/O? Name the file modes used in Python for reading, writing and appending.
Model answer
RAM is volatile, so data in variables is lost when a program ends. Disk I/O saves data permanently in files and lets programs read data created earlier or by other programs (records, logs, settings). Modes: "r" read (default), "w" write/create (overwrites), "a" append, ("x" create new only).
This lesson ends with a quiz of 8 MCQs. Open the lesson on PrepOasis to take it and save your progress.
Previous: 3.3 Advanced Data Structures in Python: Lists, Nested Lists and Dictionaries · Next: 3.5 Databases, Keys and SQL: Create, Insert, Update, Delete and Select
All lessons in Computer Science XII (HSSC-II) – FBISE Complete SLO-Based Course