AmbifulWorksheets
Practice that never repeats
CBSE · Class 12 · Computer Science

File Handling in Python

Standard difficulty · 20 questions · 40 marks · Time: 43 minutes

Name: Date: Score: ____ / 40

Show your working for Sections B and C. Answers are on the last page — try every question first!

Section A — Choose the correct answer8 × 1 = 8 marks
1.
Which file mode opens a file for writing and erases what it held?
  1. 'r'
  2. 'r+'
  3. 'a'
  4. 'w'
2.
The file notes.txt holds these lines (each ends with a newline):
Old books smell nice
Kites fly high in the sky
The test starts at nine
What does this print?
f = open('notes.txt', 'r')
c = 0
for line in f:
    if line[0] == 'T':
        c = c + 1
f.close()
print(c)
  1. 1
  2. 2
  3. 3
  4. 0
3.
The file notes.txt holds these lines (each ends with a newline):
The river flows past our town
Trees stand tall near the school
Children play in the park
What does this print?
f = open('notes.txt', 'r')
words = f.read().split()
f.close()
print(len(words))
  1. 16
  2. 3
  3. 19
  4. 17
4.
Before this runs, out.txt holds one line, Line one (with its newline). What does the program print?
f = open('out.txt', 'w')
f.write('Code\n')
for i in range(2):
    f.write('Data\n')
f.close()
f = open('out.txt')
print(len(f.read()))
f.close()
  1. 15
  2. 12
  3. 24
  4. 16
5.
What does the file mode 'a+' in open() mean?
  1. write and read; creates the file or empties it
  2. write a binary file, emptying it first
  3. read a binary file
  4. append and read; creates the file if needed
6.
The binary file marks.dat holds these records, each written with one pickle.dump(): [1, 'Ananya', 69], [2, 'Rahul', 49], [3, 'Priya', 96], [4, 'Dev', 81].
What is the last line this program prints?
import pickle
f = open('marks.dat', 'rb')
count = 0
try:
    while True:
        rec = pickle.load(f)
        if rec[2] > 77:
            print(rec[1])
            count = count + 1
except EOFError:
    f.close()
print(count)
  1. 1
  2. 4
  3. 2
  4. 3
7.
The file users.csv holds these lines:
id,name,score
U10,Vikram,44
U11,Zoya,84
U12,Rohan,94
U13,Isha,92
U14,Rahul,80
What does this print? (Output lines are separated by commas.)
import csv
f = open('users.csv', newline='')
r = csv.reader(f)
next(r)
for row in r:
    if int(row[2]) >= 94:
        print(row[1])
f.close()
  1. Vikram
  2. Vikram, Zoya, Isha, Rahul
  3. name
  4. Rohan
8.
The file notes.txt holds these lines (each ends with a newline):
Birds sing every morning
Tea is ready now
Children play in the park
What is the second line this prints?
f = open('notes.txt')
print(f.read(5))
print(f.tell())
f.seek(14)
print(f.read(4))
f.close()
  1. 6
  2. 0
  3. 5
  4. 4
Section B — Short answer8 × 2 = 16 marks
9.
What is the difference between a text file and a binary file?
10.
The file notes.txt holds these lines (each ends with a newline):
Bees make honey
Kites fly high in the sky
The bus was late today
Our garden has roses
Stars shine at night
What does this print?
f = open('notes.txt', 'r')
c = 0
for line in f:
    if line[0] == 'S':
        c = c + 1
f.close()
print(c)
11.
The file notes.txt holds these lines (each ends with a newline):
Bees make honey
Our garden has roses
The test starts at nine
A cat sleeps on the wall
Stars shine at night
What does this print? Give (a) the first line (b) the second (c) the third.
f = open('notes.txt')
print(f.read(4))
print(f.tell())
f.seek(1)
print(f.read(2))
f.close()
12.
The file notes.txt holds these lines (each ends with a newline):
Boats carry fish to the market
Mangoes ripen in summer
Tea is ready now
What does this print?
with open('notes.txt') as f:
    for line in f:
        print('#'.join(line.split()))
13.
Before this runs, out.txt holds one line, Line one (with its newline). What does the program print?
f = open('out.txt', 'a')
f.write('Stack\n')
for i in range(3):
    f.write('Files\n')
f.close()
f = open('out.txt')
print(len(f.read()))
f.close()
14.
The binary file marks.dat holds these records, each written with one pickle.dump(): [1, 'Ananya', 93], [2, 'Vikram', 58], [3, 'Zoya', 60], [4, 'Rahul', 69], [5, 'Asha', 98].
What does this program print? Write the lines separated by commas.
import pickle
f = open('marks.dat', 'rb')
count = 0
try:
    while True:
        rec = pickle.load(f)
        if rec[2] > 80:
            print(rec[1])
            count = count + 1
except EOFError:
    f.close()
print(count)
15.
The file users.csv holds these lines:
id,name,score
U10,Vikram,53
U11,Ananya,84
U12,Priya,91
U13,Rahul,38
What does this print? Write the lines separated by commas.
import csv
f = open('users.csv', newline='')
r = csv.reader(f)
next(r)
for row in r:
    if int(row[2]) >= 91:
        print(row[1])
f.close()
16.
What lines does class.csv hold after this runs? (a) How many lines? (b) Write the last line.
import csv
f = open('class.csv', 'w', newline='')
w = csv.writer(f)
w.writerow(['name', 'class', 'marks'])
w.writerows([['Arjun', 12, 49], ['Rohan', 12, 98], ['Kabir', 11, 45]])
f.close()
Section C — Word problems4 × 4 = 16 marks
17.
Write a program that reads a text file and prints the number of vowels, consonants, upper-case and lower-case letters in it.
18.
The file notes.txt holds these lines (each ends with a newline):
Kites fly high in the sky
Trees stand tall near the school
A cat sleeps on the wall
We planted ten trees
Children play in the park
A program opens notes.txt and reads it with read(). Find (a) the number of characters read, (b) the number of words, (c) the number of vowels, (d) the number of upper-case letters.
19.
The binary file marks.dat holds these records, each written with one pickle.dump(): [1, 'Ananya', 40], [2, 'Priya', 60], [3, 'Arjun', 82], [4, 'Meera', 77].
(a) What does this program print? (b) Why is the file opened twice, in two different modes?
import pickle
f = open('marks.dat', 'rb')
recs = []
try:
    while True:
        recs.append(pickle.load(f))
except EOFError:
    f.close()
for r in recs:
    if r[0] == 4:
        r[2] = r[2] + 4
f = open('marks.dat', 'wb')
for r in recs:
    pickle.dump(r, f)
f.close()
print(len(recs), recs[3])
20.
The file users.csv holds these lines:
id,name,score
U10,Vikram,67
U11,Dev,40
U12,Meera,83
U13,Ananya,50
(a) What does this program print? (b) What would happen without next(r)?
import csv
f = open('users.csv', newline='')
r = csv.reader(f)
next(r)
top = ['', '', '0']
n = 0
for row in r:
    n = n + 1
    if int(row[2]) > int(top[2]):
        top = row
f.close()
print(n)
print(top[1], top[2])
AmbifulWorksheets
Practice that never repeats
CBSE · Class 12 · Computer Science

Answer key

File Handling in Python · AW-12CS-FIL-2026-V1 · For parents — fold back or tear off before handing the sheet to your child.

QAnswerWorking
1(d) 'w'—
2(a) 1count the lines starting with T
3(d) 17split() breaks at spaces and newlines
4(a) 15'w' empties the file first, then writes 5 + 2 × 5 characters (each \n is one)
5(d) append and read; creates the file if needed'a+': append and read; creates the file if needed
6(c) 2records with marks above the limit: Priya, Dev
7(d) Rohanint() turns the score text into a number for the comparison
8(c) 5tell() gives the position after the characters already read
9A text file holds characters that people can read, in lines ending with newline characters; a binary file holds raw bytes (such as pickled objects or images) that only programs read.—
101count the lines starting with S
11(a) Bees; (b) 4; (c) eeread(n) reads n characters; seek(k) moves to position k (counting from 0)
12Boats#carry#fish#to#the#market
Mangoes#ripen#in#summer
Tea#is#ready#now
split() drops the spaces and the newline; join() puts # between the words
1333'a' keeps the old 9 characters and adds 6 + 3 × 6 characters (each \n is one)
14Ananya, Asha, 2load() reads one record each time; EOFError ends the loop
15Priyanext(r) skips the header; int() turns the score text into a number
16(a) 4; (b) Kabir,11,45writerows() writes one line per inner list, fields separated by commas: name,class,marks / Arjun,12,49 / Rohan,12,98 / Kabir,11,45
17Open with open('a.txt') as f: data = f.read(); for ch in data: if ch.isalpha(): count upper or lower with isupper(); if ch.lower() in 'aeiou' add to vowels, else to consonants. Print the four counts.—
18(a) 131; (b) 27; (c) 33; (d) 526 + 33 + 25 + 21 + 26 characters, each line counted with its newline
19(a) 4 [4, 'Meera', 81]; (b) 'rb' reads every record into a list; after the update, 'wb' empties the file and writes all the records back.roll 4: 77 + 4
20(a) 4, Meera 83; (b) the header row would be read as data, and int('score') would raise a ValueError.highest score 83