---
title: "File Handling Class 12 Computer Science: Text File Notes"
description: "File handling class 12 computer science, text files: every mode tested, read functions, seek and tell, 8 original programs with output and solved questions."
canonical: https://learn.modernagecoders.com/cbse-class-12-computer-science-file-handling
source: src/pages/cbse-class-12-computer-science-file-handling.html
---
> File handling class 12 computer science, text files: every mode tested, read functions, seek and tell, 8 original programs with output and solved questions.

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.

[![Computer Science Class 11 and 12 course thumbnail](/images/ip-cs-class-11-12.webp)  School syllabus / XI and XII Computer Science 11 and 12 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 →](/courses/cbse-icse-computer-science-class-11-12-python-java-complete-course)[![Python for Teens course thumbnail](/images/python-teens.webp)  Python / Build the habit Python for Teens 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 →](/courses/python-complete-masterclass-teens)[![MySQL for Teens course thumbnail](/images/mysql-teens.webp)  After files / Databases MySQL for Teens For the point where one text file is no longer enough: tables, keys and queries, taught from the first SELECT. Open the course →](/courses/mysql-mastery-for-teens)

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.

| 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`.

### 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.txt**file, 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.txt**file, 3 lines*

```
Water the plants daily, please.
Water bills are due; save water!
The watering can is broken.
```

***canteen.txt**file, 3 lines*

```
Idli 90
Tea 55
Poha 40
```

***need.txt**file, 4 lines*

```
rope
torch
map
whistle
```

***done.txt**file, 2 lines*

```
map
rope
```

***Six reads in a row**one 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`.

***Output**as 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 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.

### Writing: write() and writelines()

| 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 |

### 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](/cbse-class-12-computer-science-exception-handling).

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.

| B | U | S | space | 1 | 2 | space | L | A | T | E |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |

***Move, read, overwrite**mode 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())
```

***Output**as it ran*

```
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 |

### 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 1**python*

```
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"))
```

***Output**as 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 2**python*

```
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")
```

***Output**as 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 3**python*

```
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())
```

***Output**as 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 4**python*

```
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)
```

***Output**as 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 5**python*

```
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"))
```

***Output**as 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 6**python*

```
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())
```

***Output**as 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 7**python*

```
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)
```

***Output**as 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 8**python*

```
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")
```

***Output**as 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 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 | ½ | ½ |

### 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](/blog/python-practical-file-class-12) and [20 tested Python programs](/blog/python-programs-for-cbse-class-12).

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 errors**wrong 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")
```

***Corrected**python*

```
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")
```

***Output**as 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](/cbse-class-12-computer-science-csv-and-binary-files), worth nine marks in the sample paper. For one-mark practice use the [output questions](/cbse-class-12-computer-science-output-questions); for the practical, the [viva questions on files](/cbse-class-12-computer-science-viva-questions); for everything else, [important questions by unit](/cbse-class-12-computer-science-important-questions).

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](/book-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 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

## 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.

### Practicals, project and viva

- [Class 12 CS viva questions](/cbse-class-12-computer-science-viva-questions)
- [Class 12 CS project with source code](/cbse-class-12-computer-science-project-python-mysql)
- [Class 12 CS project topics](/cbse-class-12-computer-science-project-topics)

### Exam, papers and marks

- [Class 12 CS sample paper practice](/cbse-class-12-computer-science-sample-paper-2026-27)
- [Class 12 CS exam date, pattern and marks](/cbse-class-12-computer-science-paper-pattern-and-marking-scheme)
- [Class 12 CS important questions](/cbse-class-12-computer-science-important-questions)

### Questions and practice

- [Class 12 CS MCQ test](/cbse-class-12-computer-science-mcq-test)
- [Class 12 CS output questions](/cbse-class-12-computer-science-output-questions)
- [Class 12 CS case study questions](/cbse-class-12-computer-science-case-study-questions)
- [Class 12 CS SQL questions](/cbse-class-12-computer-science-sql-queries)

### Chapter by chapter

- [Functions in Python Class 12](/cbse-class-12-computer-science-functions)
- [Exception handling Class 12](/cbse-class-12-computer-science-exception-handling)
- [CSV and binary files Class 12](/cbse-class-12-computer-science-csv-and-binary-files)
- [Stack Class 12 Computer Science](/cbse-class-12-computer-science-stack)
- [Computer networks Class 12](/cbse-class-12-computer-science-computer-networks)
- [Python MySQL connectivity Class 12](/cbse-class-12-computer-science-python-mysql-connectivity)

### Notes, revision and help

- [Class 12 CS syllabus 2026-27](/cbse-class-12-computer-science-syllabus-2026-27)
- [Class 12 CS notes](/cbse-class-12-computer-science-notes)
- [Class 12 CS revision plan](/cbse-class-12-computer-science-revision-plan)
- [Class 12 CS crash course](/cbse-class-12-computer-science-crash-course)

**CBSE Class 12 Informatics Practices (065):** [Class 12 IP practical file](/cbse-class-12-informatics-practices-practical-file)  [Class 12 IP project with source code](/cbse-class-12-informatics-practices-project)  [Class 12 IP sample paper practice](/cbse-class-12-informatics-practices-sample-paper-2026-27)  [Class 12 IP important questions](/cbse-class-12-informatics-practices-important-questions)

**CBSE Class 12 Information Technology (802):** [IT 802 practical and project file](/cbse-class-12-it-802-practical-and-project-file)  [IT 802 Java notes and programs](/cbse-class-12-it-802-java-programs)  [IT 802 notes](/cbse-class-12-it-802-notes)

**CBSE Class 11 CS, IP and AI:** [Class 11 CS practical file](/cbse-class-11-computer-science-practical-file)  [Class 11 IP practical file](/cbse-class-11-informatics-practices-practical-file)  [CS or IP in Class 11](/computer-science-or-informatics-practices-class-11)

**ISC Computer Science (868):** [ISC Class 12 CS syllabus 2027](/isc-class-12-computer-science-syllabus-2027)  [ISC Class 12 CS practice paper](/isc-class-12-computer-science-specimen-paper-practice)  [ISC Class 12 practical questions solved](/isc-class-12-computer-science-practical-questions)  [ISC Boolean algebra and K-maps](/isc-class-12-computer-science-boolean-algebra)

**Program lists with output:** [Class 12 CS practical file](/blog/python-practical-file-class-12)  [20 Python programs for Class 12](/blog/python-programs-for-cbse-class-12)  [Menu-driven programs in Python](/blog/how-to-build-menu-driven-program-in-python)

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](/cbse-class-12-computer-science-functions) first.

[WhatsApp us](https://wa.me/919123366161?text=Hello%20Modern%20Age%20Coders.%20I%20want%20one%20to%20one%20classes%20on%20file%20handling%20for%20CBSE%20Class%2012%20Computer%20Science%20083.) · [+91 91233 66161](tel:+919123366161) · [connect@modernagecoders.com](mailto:connect@modernagecoders.com)

Every class is live video. The form requests a callback and reserves nothing.

### 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](/book-demo)

## Keep exploring Modern Age Coders

### By class and age

- [Number System Class 11 Computer Science: Conversions, Logic](/cbse-class-11-number-system-conversion)
- [Class 11 IP Sample Paper 2026-27 With Solution, 70 Marks](/cbse-class-11-informatics-practices-sample-paper)
- [Class 11 IP Notes 2026-27: All Four Units, With Code](/cbse-class-11-informatics-practices-notes)
- [Class 11 Computer Science Sample Paper 2026-27, Solved](/cbse-class-11-computer-science-sample-paper)
- [Class 11 Computer Science Project in Python, with Topics](/cbse-class-11-computer-science-project)
- [Class 11 Computer Science Notes 2026-27, Chapter Wise](/cbse-class-11-computer-science-notes)
- [Computer Networks Class 12 Notes: CS 083 Unit 2 for 2027](/cbse-class-12-computer-science-computer-networks)
- [Class 12 Computer Science Crash Course 2027: Live 1-on-1](/cbse-class-12-computer-science-crash-course)
- [Binary File Handling Class 12: Pickle and CSV Programs](/cbse-class-12-computer-science-csv-and-binary-files)

### Learn more

- [CS Summer Programs for High School Students: 2027 Guide](/computer-science-summer-programs-for-high-school-students)
- [AP Computer Science A Practice Questions, With Answers](/ap-computer-science-a-practice-questions)
- [The Course Atlas: Every Coding, AI & Mathematics Course (Kids, Teens](/course-atlas)
- [AI and Python Classes for Teens in Fredericton, NB](/ai-and-python-classes-for-teens-in-fredericton)

### Free resources

- [JavaScript Tutorial: Build Interactive Websites](/resources/javascript)
- [Flexbox - The Complete Guide | HTML and CSS Tutorial](/resources/html-and-css/flexbox-complete-guide)
- [ES6+ Modern JavaScript Features](/resources/javascript/es6-modern-javascript)
- [Lists and Tables](/resources/html-and-css/lists-and-tables)

### From the blog

- [Python Programs for Class 11 CBSE (CS and IP) With Output](/blog/python-programs-for-class-11)
- [Java Programs for ISC Class 11 and 12 (Solved, 2026)](/blog/java-programs-for-isc-class-11-and-12)
- [String Handling in Java: The ICSE and CBSE Guide](/blog/string-handling-in-java)

### Start here

- [About Modern Age Coders, teaching since 2020](/about)
- [Modern Age Coders pricing, one honest price per plan](/pricing)

---

*Canonical: https://learn.modernagecoders.com/cbse-class-12-computer-science-file-handling*
