loading…
CBSE Class 12 · Computer Science (083)
CBSE Class 12 Computer Science file handling in Python: text files, binary files with pickle and CSV files — programs with real output, output questions and viva answers.
def count_T(filename):
count = 0
with open(filename) as f:
for line in f:
if line.startswith("T"):
count += 1
return count
print("Lines starting with T:", count_T("story.txt"))
Output
Lines starting with T: 3
def short_words(filename):
with open(filename) as f:
for word in f.read().split():
word = word.strip(".,")
if len(word) < 4:
print(word, end=" ")
print()
short_words("story.txt")
Output
The Sun the to We all to the is fun to was a day
with open("notes.txt", "w") as f:
f.write("Python\nis\nfun\n")
with open("notes.txt") as f:
print(f.readline().strip(), len(f.readlines()))
Python 2
Why: readline() reads one line; readlines() then returns the lines that are left.
with open("a.txt", "w") as f:
f.write("ABCDEFG")
with open("a.txt") as f:
print(f.read(3), f.tell())
f.seek(5)
print(f.read())
ABC 3 FG
Why: read(3) reads 3 characters; tell() gives the position; seek() moves it.
with open("log.txt", "w") as f:
f.write("one\n")
with open("log.txt", "a") as f:
f.write("two\n")
with open("log.txt", "w") as f:
f.write("three\n")
print(open("log.txt").read().split())
['three']
Why: Mode 'a' adds to the end; mode 'w' wipes the file first.
f = open("data.txt", "w")
f.write(25)
f.close()
Running it stops with TypeError.
f = open("data.txt", "w")
f.write(str(25))
f.close()
PyRun is not affiliated with CBSE. Questions are written in the board's style for practice; they are not past papers.