13 questions from CBSE board, sample and compartment papers (2024–2027), 1 to 3 marks, each with a model answer. Questions on opening and closing text files, read(), readline() and readlines(), write() and writelines(), file modes and the file pointer (seek and tell), and functions that count or display lines and words. Programming answers open in the Python Lab.
File Handling in Python (Text File)· 1 Mark· Q16· 2024 Board Paper
Consider the following Python statement:
F=open('CONTENT.TXT')
Which of the following is an invalid statement in Python?
(A)F.seek(1,0)
(B)F.seek(0,1)
(C)F.seek(0,-1)
(D)F.seek(0,2)
Model answer
(c) F.seek(0,-1)
Explanation: The reference point (whence) for seek() must be 0 (beginning), 1 (current position), or 2 (end). -1 is invalid.
File Handling in Python (Text File)· 3 Marks· Q28· 2024 Board Paper Python
(A) Write a user defined function in Python named showInLines() which reads contents of a text file named STORY.TXT and displays every sentence in a separate line.
Assume that a sentence ends with a full stop (.), a question mark (?), or an exclamation mark (!).
For example, if the content of file STORY.TXT is as follows:
Our parents told us that we must eat vegetables to be healthy. And it turns out, our parents were right! So, what else did our parents tell?
Then the function should display the file's content as follows:
Our parents told us that we must eat vegetables to be healthy.
And it turns out, our parents were right!
So, what else did our parents tell?
OR
(B) Write a function, c_words() in Python that separately counts and displays the number of uppercase and lowercase alphabets in a text file, Words.txt.
Model answer
(A)
def showInLines():
f = open("STORY.TXT", "r")
text = f.read()
sentence = ""
for ch in text:
sentence += ch
if ch in ['.', '?', '!']:
print(sentence.strip())
sentence = ""
if sentence.strip():
print(sentence.strip())
f.close()
OR
(B)
def c_words():
f = open("Words.txt", "r")
text = f.read()
u_count = 0
l_count = 0
for ch in text:
if ch.isupper():
u_count += 1
elif ch.islower():
l_count += 1
print("Uppercase alphabets:", u_count)
print("Lowercase alphabets:", l_count)
f.close()
sample_story = "Our parents told us that we must eat vegetables to be healthy. And it turns out, our parents were right! So, what else did our parents tell?"
def showInLines_demo(text):
sentence = ""
for ch in text:
sentence += ch
if ch in ['.', '?', '!']:
print(sentence.strip())
sentence = ""
showInLines_demo(sample_story)
File Handling in Python (Text File)· 3 Marks· Q29· 2025 Board Paper Python
(a) Write a Python function that displays all the lines containing the word 'vote' from a text file "Elections.txt". For example, if the file contains:
In an election many people vote to choose their representative.
The candidate getting the maximum share of votes stands elected.
Normally, one person has to vote once.
The process of voting may vary with time and region.
Then the output should be:
In an election many people vote to choose their representative.
Normally, one person has to vote once.
def display_vote_lines():
# Mocking file content for demonstration
content = "In an election many people vote to choose their representative.\nThe candidate getting the maximum share of votes stands elected.\nNormally, one person has to vote once.\nThe process of voting may vary with time and region."
# In real file handling: with open('Elections.txt') as f:
lines = content.split('\n')
for line in lines:
if 'vote' in line:
print(line)
display_vote_lines()
File Handling in Python (Text File)· 3 Marks· Q29· 2025 Board Paper Python
(b) Write a Python function that displays all the words starting and ending with a vowel from a text file "Report.txt". The consecutive words should be separated by a space in the output. For example, if the file contains:
Once there was a wise man in a village.
He was an awesome story-teller.
He was able to keep people anchored while listening to him.
Then the output should be:
Once a a awesome able
def display_vowel_words():
# Mock file content for demonstration
content = "Once there was a wise man in a village.\nHe was an awesome story-teller.\nHe was able to keep people anchored while listening to him."
vowels = 'aeiouAEIOU'
words = content.replace('.', '').split()
for word in words:
if word[0] in vowels and word[-1] in vowels:
print(word, end=' ')
# Function call
display_vowel_words()
File Handling in Python (Text File)· 3 Marks· Q29· 2026 Board Paper Python
(a) Write a Python function that counts and returns the number of digits appearing in the text file "Space.txt". OR (b) Write a Python function that displays the words in which the lowercase letter 'e' appears at least twice in "Space.txt".
# Mocking File System
with open("Space.txt", "w") as F:
F.write("Space exploration has unlocked incredible advancements in technology and science. Since the first moon landing in 1969, space agencies have sent probes to Mars, Jupiter and beyond. The ISS, orbiting Earth at about 400 km, serves as a hub for research. With missions planned for 2030, humanity's cosmic journey continues!")
# Option (a)
def CountDigits():
with open("Space.txt", "r") as F:
Data = F.read()
count = sum(1 for ch in Data if ch.isdigit())
return count
# Option (b) (OR)
def showWords():
with open("Space.txt", "r") as F:
words = F.read().split()
for word in words:
if word.count('e') >= 2:
print(word, end=' ')
print("Digit count:", CountDigits())
print("Words with 2+ 'e's:")
showWords()
File Handling in Python (Text File)· 1 Mark· Q10· 2025 Compartment Paper Python
A text file song.txt contains the following contents in it:
Life goes on as it never ends
What will be the output of the following code snippet?
f1 = open("song.txt","r")
s1 = f1.read(5)
s2 = f1.readline(4)
s3 = f1.read(3)
print(s1, s3, sep="#")
(A)goes# on
(B)Life #goes# on
(C)Life # on
(D)Error
Model answer
Life # on
Explanation: f1.read(5) reads 'Life ' (pointer at 'g'). f1.readline(4) reads 'goes' (pointer at ' '). f1.read(3) reads ' on'. Then it prints s1 and s3 separated by #.
class MockFile:
def __init__(self, content):
self.content = content
self.ptr = 0
def read(self, n):
res = self.content[self.ptr:self.ptr+n]
self.ptr += n
return res
def readline(self, n):
res = self.content[self.ptr:self.ptr+n]
self.ptr += n
return res
f1 = MockFile("Life goes on as it never ends")
s1 = f1.read(5)
s2 = f1.readline(4)
s3 = f1.read(3)
print(s1, s3, sep="#")
File Handling in Python (Text File)· 3 Marks· Q29· 2025 Compartment Paper Python
(a) Write a Python function that displays all lines ending with a dot (.) from a text file "Colors.txt". OR (b) Write a function to display the line which has the maximum number of vowels from a text file, "Novel.txt".
# Solution for Part A
def display_dots():
# Mocked file content
content = ["White is a mix of seven colors.", "What are these seven colors ?", "VIBGYOR - violet, indigo, blue, green, orange and red.", "When we mix all these colors we", "just get one light", "which is the WHITE light."]
for line in content:
if line.strip()[-1] == '.':
print(line)
print("--- Lines ending with dot ---")
display_dots()
# Solution for Part B (OR)
def max_vowels():
content = ["This is a simple sentence.", "Here is an incredibly long and educational sentence with many vowels."]
max_v = 0
max_line = ""
for line in content:
v_count = 0
for char in line:
if char in "AEIOUaeiou":
v_count += 1
if v_count > max_v:
max_v = v_count
max_line = line
print("\n--- Max Vowels Line ---")
print(max_line)
max_vowels()
File Handling in Python (Text File)· 1 Mark· Q16· 2024 Sample Paper
Which of the following functions changes the position of file pointer and returns its new position?
(A)a. flush()
(B)b. tell()
(C)c. seek()
(D)d. offset()
Model answer
Option c
seek()
Explanation: The seek(offset, whence) method alters the current file pointer position and returns the new absolute byte offset.
File Handling in Python (Text File)· 3 Marks· Q28· 2024 Sample Paper
Write a function in Python to read a text file, Alpha.txt and displays those lines which begin with the word ‘You’.
OR
Write a function, vowelCount() in Python that counts and displays the number of vowels in the text file named Poem.txt.
Model answer
def test():
fObj1 = open("Alpha.txt","r")
data = fObj1.readlines()
for line in data:
L=line.split()
if L[0]=="You":
print(line)
fObj1.close()
OR
def vowelCount():
fObj = open("Alpha.txt","r")
data = str(fObj.read())
cnt=0
for ch in data:
if ch in "aeiouAEIOU":
cnt=cnt+1
print(cnt)
fObj.close()
Note: Any other correct logic may be marked
def test():
fObj1 = open("Alpha.txt","r")
data = fObj1.readlines()
for line in data:
L=line.split()
if len(L) > 0 and L[0]=="You":
print(line)
fObj1.close()
File Handling in Python (Text File)· 1 Mark· Q10· 2025 Sample Paper
Write the missing statement to complete the following code:
file = open("example.txt", "r")
data = file.read(100)
____________________ #Move the file pointer to the beginning of the file
next_data = file.read(50)
file.close()
Model answer
file.seek(0)
# Assuming file object is 'file'
# file.seek(0)
File Handling in Python (Text File)· 3 Marks· Q29· 2025 Sample Paper
A) Write a Python function that displays all the words containing @cmail from a text file "Emails.txt".
OR
B) Write a Python function that finds and displays all the words longer than 5 characters from a text file "Words.txt".
# (A)
def show_cmail():
f = open("Emails.txt", "r")
for word in f.read().split():
if "@cmail" in word:
print(word)
f.close()
# OR (B)
def long_words():
f = open("Words.txt", "r")
for word in f.read().split():
if len(word) > 5:
print(word)
f.close()
File Handling in Python (Text File)· 3 Marks· Q29· 2026 Sample Paper Python
A. Write a Python function that displays the number of times the word "Python" appears in a text file named "Prog.txt".
OR
B. Write and call a Python function to read lines from a text file STORIES.TXT and display those lines which doesn't start with a vowel (A, E, I, O, U) irrespective of their case.
def count_python():
# Mock file content
content = "Python is fun. I love Python programming."
count = 0
words = content.split()
for word in words:
if word.lower() == "python":
count += 1
print("The word Python appears", count, "times.")
count_python()
File Handling in Python (Text File)· 3 Marks· Q29· 2027 Sample Paper
A. Write and call a Python function to read "History.txt" and display all lines that contain a four-digit year (e.g., 1999, 2024 etc.)
OR
B. Write a Python function that displays the number of times the word "Python" appears in a text file named "Prog.txt".
Model answer
A.
def DisplayYearLines( ):
f = open("History.txt", "r")
for line in f:
words = line.split()
for w in words:
if w.isdigit() and len(w) == 4:
print(line)
break
f.close()
DisplayYearLines( )
OR
B.
def count_python():
count = 0
with open("Prog.txt", 'r') as file:
text = file.read()
words = text.split()
for word in words:
if word.lower() == "python":
count += 1
print("The word Python appears", count, "times.")
def DisplayYearLines( ):
f = open("History.txt", "r")
for line in f:
words = line.split()
for w in words:
if w.isdigit() and len(w) == 4:
print(line)
break
f.close()
DisplayYearLines( )