CBSE Class 12 · Computer Science, code 083 · Unit 1, text files

File handling class 12 computer science: text files, tested line by line.

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

Courses for a student learning to handle files

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.

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?

What is file handling in Class 12, and which text file modes are in the syllabus?

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.

ModeIf the file is missingPointer starts atread() straight awaygate.txt after write("NO")
rFileNotFoundError0'OPEN'OPEN, because writing is refused
r+FileNotFoundError0'OPEN'NOEN, two letters written over
wcreated0refused: not readableNO, the old text is gone
w+created0'', the file was just emptiedNO
acreated4, the endrefused: not readableOPENNO
a+created4, the end'', nothing after the endOPENNO

A refusal here is io.UnsupportedOperation. If no mode is given, open("gate.txt") means r.

Must the file exist?

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.

Is old data safe?

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.

Relative or absolute path?

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?

File handling in Python Class 12 notes: reading a text file

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.

trail.txtfile, 5 lines
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.

notice.txtfile, 3 lines
Water the plants daily, please.
Water bills are due; save water!
The watering can is broken.
canteen.txtfile, 3 lines
Idli 90
Tea 55
Poha 40
need.txtfile, 4 lines
rope
torch
map
whistle
done.txtfile, 2 lines
map
rope
Six reads in a rowone open file
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.

Outputas it ran
'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 ''.

Characters, words and lines: the counting idioms

You needWriteOn trail.txtWatch for
Characterslen(f.read())103Every newline and space is counted
Characters, no spaces or newlineslen("".join(f.read().split()))81Or count in a loop, skipping spaces
Wordslen(f.read().split())21split() with no argument also splits at newlines; "2" is a word
Lineslen(f.readlines())5The blank line is a line
Non-blank linesloop, test line.strip() != ""4A 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.

Writing: write() and writelines()

Call on a new fileFile 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

Closing, and why with is safer

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?

Seek and tell Class 12: the file pointer, traced

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.

BUSspace12spaceLATE
012345678910
Move, read, overwritemode r+
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())
Outputas it ran
0
BUS
3
LATE
11
BUS 45 LATE
After the linePointerWhy
open in r+0r and r+ start at the beginning
read(3)3Three characters passed
seek(7)7On the L
read()11Read to the end
seek(4), write("45")6Two characters written over 1 and 2
seek(0)0Back to the start to read again

The second argument

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.

w+ needs a seek

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.

a+ reads, but writes at the end

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?

Text file programs Class 12, with the output each one gave

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.

1. Count one word, ignoring case and punctuation

Program 1python
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"))
Outputas it ran
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".

2. Show the lines longer than a limit

Program 2python
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")
Outputas it ran
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.

3. Copy a file with line numbers, skipping blanks

Program 3python
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())
Outputas it ran
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.

4. Find the longest word and its line

Program 4python
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)
Outputas it ran
temple on line 1

banyan has six letters too, but > keeps the first. With >= the function would report the last.

5. Add the numbers in a file, and survive a missing file

Program 5python
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"))
Outputas it ran
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.

6. Replace text in a file

Program 6python
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())
Outputas it ran
Changes: 1
Idli 90
Tea 55
Upma 40

Read everything, close, then write everything. Opening in w first would leave nothing to read.

7. Show the last n lines

Program 7python
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)
Outputas it ran
Keep left at the old banyan
Water point near the lake

readlines() gives a list, so list slicing works. end="" stops the double spacing.

8. Compare two files

Program 8python
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")
Outputas it ran
Pack: torch
Pack: whistle

Both sides must be clean of newlines. "rope\n" in done is False even though "rope" is in the file.

How three marks are divided

Step in the official 2026-27 scheme, Question 29Marks in AMarks in B
Function header½½
File opened correctly½½
Reading the filein logic½
Splitting into wordsin logic½
Logic or counter1½½
Call, or display of the result½½

Reading the task first

  • Display or return? Count what the question says. Returning a value nobody prints shows nothing.
  • Word or part of a word? Whole words need split(); a letter needs a loop over characters.
  • Same case? If the question gives both "The" and "the", lower both sides.
  • Write and call? Then the call carries half a mark.

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?

File handling Class 12 important questions, with answers

Text files appear as one-mark outputs, two-mark differences and the three-mark program. Answer these on paper before opening them.

One mark

  1. Which mode opens an existing text file for reading and writing without erasing it: w+, r+, a or w?
    Answer r+. The file must already exist, and the pointer starts at 0.
  2. What does print(f.write("Sun\n")) display, where f is open in w mode?
    Answer 4. write() returns the number of characters written, and \n is one character.
  3. A file has two lines. What does the third call to readline() return?
    Answer An empty string, ''. It is not an error.
  4. Fill in the blank: f.______(0) takes the pointer back to the beginning.
    Answer seek.
  5. f.writelines("abc") is called on a new file. What does the file hold?
    Answer abc. A string is a sequence of characters, so each is written in turn, with nothing between them.
  6. Assertion: A file opened with with is closed even if the block raises an error. Reason: with stops errors from being raised.
    Answer A is true, R is false. The file is closed, but the error still goes on to the caller unless it is handled.
  7. What is the type of f.readlines(), and of its first item?
    Answer list, and str.

Two marks

  1. Differentiate between w and a modes.
    Answer Both create a missing file and both only write. 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.
  2. Differentiate between r+ and w+, with an example of each.
    Answer r+ needs the file to exist and keeps its content: open("marks.txt", "r+"). w+ creates or empties it: open("marks.txt", "w+"). Both allow reading and writing.
  3. Why should a file be closed? Give two reasons.
    Answer Closing sends any text still waiting in memory to the file, and it frees the file so that another program can use it.
  4. What is wrong with open("D:\test\new.txt")? Write it correctly in two ways.
    Answer \t is read as a tab and \n as a newline. Write open("D:\\test\\new.txt") or open(r"D:\test\new.txt").

Find four errors (two marks)

The function should display the number of lines of a file that end with a full stop.

With errorswrong on purpose
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")
Correctedpython
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")
Outputas it ran
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.

Three marks, to write yourself

  1. Display the words of trail.txt that have exactly four letters, and how many there are.
    Answer Read and split, test len(word) == 4, print and count. On our file: gate, Keep, left, near and lake, so the count is 5.
  2. Write to short.txt only those lines of notice.txt with fewer than 30 characters, not counting the newline.
    Answer Two files open together, len(line.strip()) < 30, then fout.write(line). One line qualifies: "The watering can is broken." with 27.
  3. Display the item with the highest amount in canteen.txt.
    Answer Keep 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.

Say the pointer aloud

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.

Write, then break it

Each program is run on a normal file, an empty one, one with blank lines, and a name that does not exist.

Half marks in the margin

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

Learn the file chapter with one teacher and one screen

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

Priority demo, at a slot you pick

a full live class of about 45 to 60 minutes

  • You write one text file program while the teacher watches
  • The same program is tried on an empty file and a missing one
  • Your answer is marked in half marks, as the scheme does it
  • A skill report in writing says which file skills hold and which do not
Book a priority demo

The classes · Choose your own timing

Personalised one to one

₹4,999

per month, 4 private classes, fully flexible timing

  • Text files first, then pickle and CSV, at your own pace
  • Your school worksheet or report file programs used as material
  • A pointer trace before every seek and tell question
  • Older gaps in strings and loops repaired when they show up
Ask for a personalised plan

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?

File handling classes for CBSE students abroad

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 liveTime differenceUsual class window, local timeFormat
India
every Indian city
Indian timeAny time you choosePersonalised 1-on-1
UAE and Oman
Dubai, Abu Dhabi, Sharjah, Muscat
1 h 30 min behind India3:00 PM to 9:00 PMPersonalised 1-on-1
Saudi Arabia, Qatar, Kuwait, Bahrain
Riyadh, Jeddah, Dammam, Doha, Kuwait City, Manama
2 h 30 min behind India3:00 PM to 9:00 PMPersonalised 1-on-1
Nepal
Kathmandu
15 min ahead of India4:30 PM to 9:00 PMPersonalised 1-on-1
Ethiopia and East Africa
Addis Ababa and East Africa Time
2 h 30 min behind India4:30 PM to 9:00 PMPersonalised 1-on-1
Singapore and Malaysia
Singapore, Kuala Lumpur
2 h 30 min ahead of India3:30 PM to 9:00 PMPersonalised 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

Rated 4.9 across 547 Google reviews

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

More pages for Class 12 students

Every page in the CBSE Class 12 Computer Science series, grouped by what you need.

Questions about text files

What students ask about file handling in Class 12

What is file handling in Class 12 Computer Science?

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.

How many marks does file handling carry in the Class 12 CS paper?

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.

What are the modes of opening a text file in Python?

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.

What is the difference between seek() and tell()?

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.

What is the difference between read(), readline() and readlines()?

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.

Why does my program print a blank line after every line of the file?

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.

Is with open() better than open() and close() in the board exam?

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.

What is the difference between w and a mode?

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.

Which text file programs are important for Class 12?

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.

Do I need to handle FileNotFoundError in a text file answer?

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.

Can I learn file handling one to one before the practical?

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

Open one file with us

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.

We call within a few hours. No card, no enrolment fee.

Want it sooner? Book a priority demo

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

Keep exploring Modern Age Coders

By class and age

Learn more

Free resources

From the blog

Start here