★★★★★
"The one step solution for my son. Modern Age Coders make learning coding so simple that kids love it. The teachers explain complex concepts clearly with practical exercises and interactive content."
Ria Mukherjee
Parent
CBSE Class 12 · Computer Science, code 083 · Unit 1, text files
File handling in class 12 computer science becomes easy once you can say two things about any line of code: which mode the file is in, and where the pointer is standing. These notes cover text files for CBSE 083 in that order, with small data files you can retype, eight programs of the three-mark kind, and the output each one really gave.
Live one to one · 8 original programs · every mode tested on the same file · your own days and hours
Start here
One course follows the school syllabus from start to finish. The other two suit a student whose Python basics are shaky, or one who wants the next step after files: a database.

School syllabus / XI and XII
File handling sits here in its place, after functions and before the stack, with SQL, networks and Python to MySQL connectivity following.
Open the course →
Python / Build the habit
Has its own unit on reading and writing text files, the with statement and CSV, used inside projects such as an expense tracker.
Open the course →
After files / Databases
For the point where one text file is no longer enough: tables, keys and queries, taught from the first SELECT.
Open the course →Ans. The short version
File handling in Class 12 Computer Science (CBSE 083) means storing data in a text, binary or CSV file so that it is still there after the program ends. For text files you need six modes (r, r+, w, w+, a, a+), read(), readline() and readlines(), write() and writelines(), the with clause, and seek() and tell(). The 2026-27 sample paper has a three-mark text file program, Question 29. Modern Age Coders teaches the chapter live, personalised one to one at your own timing. A priority demo lets you try one full class first.
Q1. Which mode, and what does it do to the file?
File handling is opening a file, reading from it or writing to it, and closing it again. The 083 syllabus lists three file types, text, binary and CSV, and six modes for text files: r, r+, w, w+, a and a+.
We put the same four letters, OPEN, in a file called gate.txt. For each mode we opened it, tried to read at once, then started again and tried f.write("NO"). This is what Python did.
| Mode | If the file is missing | Pointer starts at | read() straight away | gate.txt after write("NO") |
|---|---|---|---|---|
r | FileNotFoundError | 0 | 'OPEN' | OPEN, because writing is refused |
r+ | FileNotFoundError | 0 | 'OPEN' | NOEN, two letters written over |
w | created | 0 | refused: not readable | NO, the old text is gone |
w+ | created | 0 | '', the file was just emptied | NO |
a | created | 4, the end | refused: not readable | OPENNO |
a+ | created | 4, the end | '', nothing after the end | OPENNO |
A refusal here is io.UnsupportedOperation. If no mode is given, open("gate.txt") means r.
Only the two r modes insist. The w and a modes quietly make a new file, so a spelling mistake in the name gives you an empty second file and no error.
It is lost at the moment of opening in w or w+, before any write. In r+ it is overwritten only where you write. In a and a+ it stays.
data/trail.txt is relative: it starts from the current folder. C:\school\trail.txt is absolute: it starts from the drive.
A path that is not what you typed. print("C:\new\trail.txt") shows C:, then a new line, then ew, a tab and rail.txt, because \n and \t are escape sequences. Double each backslash, or put r before the opening quote: r"C:\new\trail.txt".
Q2. read, readline or readlines?
read() gives one string, readline() gives one line as a string, and readlines() gives a list of lines. All three continue from wherever the pointer was left.
Save these data files once. The programs further down use them too.
Start at the temple gate Water point after 2 km Keep left at the old banyan Water point near the lake
The third line is blank, on purpose.
Water the plants daily, please. Water bills are due; save water! The watering can is broken.
Idli 90 Tea 55 Poha 40
rope torch map whistle
map rope
with open("trail.txt", "r") as f:
print(repr(f.read(5)))
print(repr(f.readline()))
print(repr(f.readline()))
print(repr(f.readline()))
print(len(f.readlines()))
print(repr(f.read()))repr() is only used to make each newline visible as \n.
'Start' ' at the temple gate\n' 'Water point after 2 km\n' '\n' 2 ''
readline() finishes the line that read(5) began. A blank line is '\n'. Only the end of the file is ''.
| You need | Write | On trail.txt | Watch for |
|---|---|---|---|
| Characters | len(f.read()) | 103 | Every newline and space is counted |
| Characters, no spaces or newlines | len("".join(f.read().split())) | 81 | Or count in a loop, skipping spaces |
| Words | len(f.read().split()) | 21 | split() with no argument also splits at newlines; "2" is a word |
| Lines | len(f.readlines()) | 5 | The blank line is a line |
| Non-blank lines | loop, test line.strip() != "" | 4 | A blank line is not an empty string, it is a newline |
Do not run two of these on one open file. After the first, the pointer is at the end and the second sees nothing.
| Call on a new file | File then holds |
|---|---|
f.write("Tea"); f.write("Milk") | TeaMilk |
f.writelines(["Tea", "Milk"]) | TeaMilk, no newline is added |
f.writelines(["Tea\n", "Milk\n"]) | Two lines |
f.write(45) | TypeError: write() argument must be str, not int |
Text you write may wait in memory and reach the file only when it is closed. f.close() does that. A with block does it for you, even if an error stops the block half way.
After the block, f.closed is True and f.read() raises ValueError: read of closed file. The usual cause is a read line indented one step too little.
What finally does with a file is on exception handling for Class 12.
Q3. Where is the file pointer now?
tell() returns the current position of the file pointer, and seek(n) moves the pointer to position n, counted in bytes from the start of the file, which is 0.
The file bus.txt holds one line with no newline at the end: BUS 12 LATE, eleven characters at positions 0 to 10.
| B | U | S | space | 1 | 2 | space | L | A | T | E |
|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
with open("bus.txt", "w") as f:
f.write("BUS 12 LATE")
with open("bus.txt", "r+") as f:
print(f.tell())
print(f.read(3))
print(f.tell())
f.seek(7)
print(f.read())
print(f.tell())
f.seek(4)
f.write("45")
f.seek(0)
print(f.read())0 BUS 3 LATE 11 BUS 45 LATE
| After the line | Pointer | Why |
|---|---|---|
| open in r+ | 0 | r and r+ start at the beginning |
| read(3) | 3 | Three characters passed |
| seek(7) | 7 | On the L |
| read() | 11 | Read to the end |
| seek(4), write("45") | 6 | Two characters written over 1 and 2 |
| seek(0) | 0 | Back to the start to read again |
seek(offset, 0) counts from the start, 1 from the present position and 2 from the end. In a text file only seek(0, 2) works with 2, and it jumps to the end. seek(-4, 2) raises UnsupportedOperation there, though it is fine in rb.
Write SHUT in w+ and read at once: you get an empty string, since the pointer is after the T. f.seek(0) and read again gives SHUT.
With OPEN in the file, f.seek(0) lets you read it. A second seek(0) followed by write("!") still gives OPEN!. Append means append.
On Windows, a newline in a text file is stored as two bytes, so tell() after a line break can be larger than the number of characters you counted. Within the first line, the numbers match.
Q4. Can you write it in eight minutes?
A three-mark text file program has four parts: the function header, opening the file in the right mode, the logic, and the result or the call. These eight use the data files above and no other.
def count_word(filename, target):
"""Return how often target occurs as a whole word."""
count = 0
with open(filename, "r") as f:
for word in f.read().split():
if word.strip(".,;:!?").lower() == target:
count += 1
return count
print("water:", count_word("notice.txt", "water"))water: 3
The notice has Water, Water and water! as whole words. f.read().lower().count("water") would say 4, because it also finds the first half of "watering".
def long_lines(filename, limit=22):
"""Display lines with more than limit characters."""
shown = 0
with open(filename, "r") as f:
for line in f:
text = line.strip() # newline not counted
if len(text) > limit:
print(len(text), text)
shown += 1
print("Lines shown:", shown)
long_lines("trail.txt")24 Start at the temple gate 27 Keep left at the old banyan 25 Water point near the lake Lines shown: 3
"Water point after 2 km" has exactly 22 characters, so "more than 22" leaves it out. Without strip() the newline would make it 23 and the answer would be wrong.
def number_lines(source, target):
"""Write the non-blank lines of source, numbered."""
number = 0
with open(source, "r") as fin, open(target, "w") as fout:
for line in fin:
if line.strip() != "":
number += 1
fout.write(str(number) + ". " + line)
number_lines("trail.txt", "numbered.txt")
with open("numbered.txt", "r") as f:
print(f.read())1. Start at the temple gate 2. Water point after 2 km 3. Keep left at the old banyan 4. Water point near the lake
No "\n" is added in the write, because line still carries its own.
def longest_word(filename):
"""Return the longest word and its line number."""
best = ""
where = 0
with open(filename, "r") as f:
lines = f.readlines()
for i in range(len(lines)):
for word in lines[i].split():
if len(word) > len(best):
best = word
where = i + 1 # people count from 1
return best, where
word, line = longest_word("trail.txt")
print(word, "on line", line)temple on line 1
banyan has six letters too, but > keeps the first. With >= the function would report the last.
def day_total(filename):
"""Return the sum of the last value on each line."""
total = 0
try:
with open(filename, "r") as f:
for line in f:
parts = line.split()
total += int(parts[-1])
except FileNotFoundError:
print(filename, "is not in this folder")
finally:
print("Finished with", filename)
return total
print(day_total("canteen.txt"))
print(day_total("canten.txt"))Finished with canteen.txt 185 canten.txt is not in this folder Finished with canten.txt 0
Every value read from a text file is a string, so int() is needed before adding.
def replace_text(filename, old, new):
"""Change old to new everywhere in the file."""
with open(filename, "r") as f:
content = f.read()
changes = content.count(old)
with open(filename, "w") as f:
f.write(content.replace(old, new))
return changes
print("Changes:", replace_text("canteen.txt", "Poha", "Upma"))
with open("canteen.txt", "r") as f:
print(f.read())Changes: 1 Idli 90 Tea 55 Upma 40
Read everything, close, then write everything. Opening in w first would leave nothing to read.
def last_lines(filename, n):
"""Display the last n lines of the file."""
with open(filename, "r") as f:
lines = f.readlines()
for line in lines[-n:]:
print(line, end="")
last_lines("trail.txt", 2)Keep left at the old banyan Water point near the lake
readlines() gives a list, so list slicing works. end="" stops the double spacing.
def still_to_pack(need_file, done_file):
"""Display items in need_file missing from done_file."""
with open(done_file, "r") as f:
done = f.read().split()
with open(need_file, "r") as f:
for line in f:
item = line.strip()
if item not in done:
print("Pack:", item)
still_to_pack("need.txt", "done.txt")Pack: torch Pack: whistle
Both sides must be clean of newlines. "rope\n" in done is False even though "rope" is in the file.
| Step in the official 2026-27 scheme, Question 29 | Marks in A | Marks in B |
|---|---|---|
| Function header | ½ | ½ |
| File opened correctly | ½ | ½ |
| Reading the file | in logic | ½ |
| Splitting into words | in logic | ½ |
| Logic or counter | 1½ | ½ |
| Call, or display of the result | ½ | ½ |
For the syllabus tasks your report file must show, such as words separated by #, see the Class 12 practical file and 20 tested Python programs.
Q5. What will the paper ask?
Text files appear as one-mark outputs, two-mark differences and the three-mark program. Answer these on paper before opening them.
print(f.write("Sun\n")) display, where f is open in w mode? \n is one character.readline() return? ''. It is not an error.f.______(0) takes the pointer back to the beginning. f.writelines("abc") is called on a new file. What does the file hold? with is closed even if the block raises an error. Reason: with stops errors from being raised. f.readlines(), and of its first item? w and a modes. w empties an existing file and writes from position 0; a keeps the content and writes at the end. Use w for a fresh bill, a for a running log.r+ and w+, with an example of each. open("marks.txt", "r+"). w+ creates or empties it: open("marks.txt", "w+"). Both allow reading and writing.open("D:\test\new.txt")? Write it correctly in two ways. \t is read as a tab and \n as a newline. Write open("D:\\test\\new.txt") or open(r"D:\test\new.txt").The function should display the number of lines of a file that end with a full stop.
def stops(filename)
count = 0
with open(filename, "w") as f:
for line in f:
if line[-1] == ".":
count = count + 1
print(Count)
stops("notice.txt")def stops(filename): # colon added
count = 0
with open(filename, "r") as f: # r, not w
for line in f:
if line.strip()[-1:] == ".": # newline off
count = count + 1
print(count) # small c
stops("notice.txt")2
The third error is the logical one: the last character of a line is normally its newline. The slice [-1:] also survives a blank line, where [-1] would raise IndexError.
len(word) == 4, print and count. On our file: gate, Keep, left, near and lake, so the count is 5.len(line.strip()) < 30, then fout.write(line). One line qualifies: "The watering can is broken." with 27.best = 0 and the name; on each line split into two parts, convert the second with int() and compare. The answer is Idli with 90.In class the student reads a program and calls out the position after each line. It takes ten minutes and it settles most of the output questions.
Each program is run on a normal file, an empty one, one with blank lines, and a name that does not exist.
A handwritten answer is marked with the scheme beside it, so a forgotten call or close is seen as the half mark it is.
Next in the chapter: CSV and binary files, worth nine marks in the sample paper. For one-mark practice use the output questions; for the practical, the viva questions on files; for everything else, important questions by unit.
One to one, at your own timing
File mistakes are private ones: your folder, your path, your forgotten strip(). So the class is yours alone, personalised one to one, on the days and at the hour you name. You can begin with a priority demo, where the fee comes off your first month if you enrol, or with a free demo class. You pay by the month, nothing is charged for admission, and you may stop at the end of any month.
Before you enrol · Try a class
a full live class of about 45 to 60 minutes
The classes · Choose your own timing
₹4,999
per month, 4 private classes, fully flexible timingtwo private classes a week, at a time set with you
A student who finds files hard is sometimes really stuck on strings: split, strip and slicing. The first class finds out which it is, and the plan follows from that. The monthly fee on this page is shown in the currency of your country.
Studying outside India?
The 083 paper of a student in Doha or Kuwait has the same file questions as one in Jaipur. Choose an evening that suits your school week and keep it.
| Where you live | Time difference | Usual class window, local time | Format |
|---|---|---|---|
| India every Indian city | Indian time | Any time you choose | Personalised 1-on-1 |
| UAE and Oman Dubai, Abu Dhabi, Sharjah, Muscat | 1 h 30 min behind India | 3:00 PM to 9:00 PM | Personalised 1-on-1 |
| Saudi Arabia, Qatar, Kuwait, Bahrain Riyadh, Jeddah, Dammam, Doha, Kuwait City, Manama | 2 h 30 min behind India | 3:00 PM to 9:00 PM | Personalised 1-on-1 |
| Nepal Kathmandu | 15 min ahead of India | 4:30 PM to 9:00 PM | Personalised 1-on-1 |
| Ethiopia and East Africa Addis Ababa and East Africa Time | 2 h 30 min behind India | 4:30 PM to 9:00 PM | Personalised 1-on-1 |
| Singapore and Malaysia Singapore, Kuala Lumpur | 2 h 30 min ahead of India | 3:30 PM to 9:00 PM | Personalised 1-on-1 |
You need a laptop with Python and a microphone. The teacher sees your screen and your folder, which is where most file errors are hiding.
What families say
Real reviews from real families. We neither write nor commission them.
★★★★★
"The one step solution for my son. Modern Age Coders make learning coding so simple that kids love it. The teachers explain complex concepts clearly with practical exercises and interactive content."
Ria Mukherjee
Parent
★★★★★
"Modern Age Coders has been a game-changer for me. I struggled to grasp IT concepts and coding before joining, but their classes transformed everything. I can now confidently write complex programs with ease."
Samriddha Mondal
Student
★★★★★
"One of the most wonderful education centres out there. Education is not limited to school syllabus but focuses on skill development."
Vansh Agarwal
Student
★★★★★
"My child Dhairya is really enjoying the Modern Age Coders classes. This is his first online class and he eagerly looks forward to it. I can already see his improvement, and the teachers are very cooperative."
Sonam Oswal
Parent of Dhairya
★★★★★
"Modern Age Coders have wonderful teachers who teach in a clear, easy and practical way. The teacher boosts students' confidence and inspires them to learn without hesitation."
Sonu Goyal
Parent
★★★★★
"I highly recommend this computer coding class! The teachers are incredibly knowledgeable and passionate about coding."
Ritu Kedia
Parent
The rest of the Class 12 series
Every page in the CBSE Class 12 Computer Science series, grouped by what you need.
CBSE Class 12 Informatics Practices (065): Class 12 IP practical file Class 12 IP project with source code Class 12 IP sample paper practice Class 12 IP important questions
CBSE Class 12 Information Technology (802): IT 802 practical and project file IT 802 Java notes and programs IT 802 notes
CBSE Class 11 CS, IP and AI: Class 11 CS practical file Class 11 IP practical file CS or IP in Class 11
ISC Computer Science (868): ISC Class 12 CS syllabus 2027 ISC Class 12 CS practice paper ISC Class 12 practical questions solved ISC Boolean algebra and K-maps
Program lists with output: Class 12 CS practical file 20 Python programs for Class 12 Menu-driven programs in Python
Questions about text files
File handling is the part of Unit 1 of CBSE 083 that deals with storing data permanently. You open a file in a suitable mode, read or write, and close it. The 2026-27 syllabus covers three types, text files, binary files with the pickle module, and CSV files with the csv module, along with relative and absolute paths.
CBSE does not fix a mark for the chapter alone. In the 2026-27 sample paper, files appear in Question 14 (1 mark), 20 (1), 29 (3), 33 (4) and 36 (5), which is 14 marks, plus an optional two-mark question on seek and tell. Unit 1 as a whole is 40 marks.
The syllabus lists six: r to read, r+ to read and write an existing file, w to write a new or emptied file, w+ to write and read a new or emptied file, a to add at the end, and a+ to add at the end and read. If you leave the mode out, Python uses r.
tell() takes no argument and returns the present position of the file pointer as a number. seek(n) moves the pointer to position n from the beginning. One reports, the other moves. A common pair of lines is position = f.tell() before a read, and f.seek(position) to go back to the same place.
read() returns the rest of the file as one string, or n characters if you write read(n). readline() returns the next line as a string with its newline. readlines() returns all the remaining lines as a list of strings. At the end of the file they give an empty string, an empty string and an empty list.
Each line read from the file already ends with a newline, and print() adds another. Use print(line, end="") or print(line.strip()). Use strip() as well when you compare, because "exit" and "exit" with a newline are not equal.
Both are accepted. The 2026-27 marking scheme uses each of them in different answers. with closes the file for you, so there is no closing line to forget, and it is one line shorter. If you use open(), write f.close() at the end.
w empties the file as soon as it opens and writes from the start. a keeps what is there and adds at the end. Both create the file if it does not exist, and neither can read. Running a w program twice leaves one copy of the data; running an a program twice leaves two.
Practise the kinds: counting a word, letter or line; displaying lines that meet a condition; copying selected lines to another file; replacing text; and adding numbers stored in a file. The syllabus practical list names three: words separated by #, counting vowels and cases, and removing lines that contain the letter a.
Only if the question asks for it or mentions exceptions. The text file steps in the 2026-27 scheme give marks for header, opening, logic and call, not for a try block. In the practical it is worth adding, since a program that fails politely shows better code quality.
Yes. Classes are live and personalised one to one, on days you choose. Start with a priority demo, a full class of about 45 to 60 minutes with a written skill report, whose fee is adjusted in the first month if you enrol, or take a free demo class. CBSE schedules regular-school practicals from 1 January 2027.
Start
In the free demo class, write any short text file program and run it on your own laptop. The teacher asks what the pointer is doing and why you chose the mode.
A priority demo is a whole class at a slot you choose: one program of the three-mark kind from blank page to marked answer, the errors that came up explained, and a written skill report sent afterwards. Its fee is taken off the first month if you continue.
If functions are the part that slows you, look at functions in Python for Class 12 first.
WhatsApp us · +91 91233 66161 · connect@modernagecoders.com
Every class is live video. The form requests a callback and reserves nothing.
A full live class of about 45 to 60 minutes at a slot you pick, with a written skill report and learning roadmap on WhatsApp afterwards. The fee is adjusted against your first month if you enrol.
Book a priority demo