Skip to content
Computer ScienceCBSE Class 12 · File Handling in Python

Text File Read and Write Programs in Python (Class 12 Computer Science)

Updated 16 October 2026 · Fact-checked

A text file is opened with open(name, mode), where 'r' reads, 'w' overwrites or creates, and 'a' adds at the end. read() returns the whole text as one string, readline() returns one line, and readlines() returns a list of lines. write() and writelines() add text without adding new lines. Close the file, or use with to close it automatically.

Understand Text File Read and Write Programs

A text file stores characters, organised in lines that end with the newline character \n (NCERT 2.2.1). To work with it, open it to get a file object: f = open('story.txt', 'r'), and close it with f.close() when finished. With with open('story.txt') as f: the file is closed automatically when the block ends (NCERT 2.3.3).

Modes (NCERT Table 2.1): 'r' read only (the default; error if the file is missing); 'r+' read and write, file must exist; 'w' write: creates the file or erases an existing one; 'w+' write and read, also erasing; 'a' append: creates the file if needed and writes at the end; 'a+' append and read. In r, r+, w and w+ the file pointer starts at the beginning; in a and a+ it starts at the end.

Reading (NCERT 2.5):

  • f.read() returns the whole remaining text as one string; f.read(n) returns the next n characters.
  • f.readline() returns the next line including its \n; at the end of the file it returns ''.
  • f.readlines() returns a list of all remaining lines, each with its \n.
  • for line in f: visits the lines one by one, the usual choice in programs.

Each read continues from where the previous one stopped.

Writing (NCERT 2.4): f.write(s) writes the string s and returns the number of characters written; it does not add \n, so write it yourself. f.writelines(L) writes every string in the list L, again with no newlines added. Numbers must be converted with str() before writing.

Position (NCERT 2.6): f.tell() gives the current position of the file pointer; f.seek(n) moves it to position n from the beginning (seek(offset, 0); reference points 1 and 2 mean current position and end, which in text mode can be used only with offset 0).

Board program patterns (Q29-type, 3 marks): read the file and

  • count lines, words or characters: len(f.readlines()), len(f.read().split()), len(f.read())
  • display lines that start with a letter: if line[0] in 'Tt': or line.startswith(...)
  • count a word: split each line and compare w.lower() == 'the'
  • show lines containing a digit, or copy chosen lines to another file opened in 'w' mode.

Strip the newline with line.strip() or print(line, end='') to avoid blank lines in the output.

Text File Read and Write Programs: key facts

Text file modes
  • r: read only; file must exist; pointer at start
  • r+: read and write; file must exist; pointer at start
  • w: write; creates or erases the file
  • w+: write and read; creates or erases
  • a: append; creates if missing; pointer at end
  • a+: append and read; pointer at end
NCERT Table 2.1; 'r' is the default mode.
Reading methods
read()rest of the file as one string
read(n)next n characters
readline()next line with its newline, '' at the end
readlines()list of the remaining lines
for line in fone line at a time
Each read starts where the last one stopped.
Writing methods
write(s)writes s and returns its length; no newline added
writelines(list)writes each string; no newline added
str(n)convert numbers before writing
Add '\n' yourself to start a new line.
Pointer methods
tell()current position
seek(n) or seek(n, 0)move to position n from the start
seek(0)back to the beginning
In text mode, seek relative to the current position or the end works only with offset 0.
Counting patterns
lineslen(f.readlines())
wordslen(f.read().split())
characterslen(f.read())
a wordsum of w.lower() == 'the' over every split word
read() once per pattern, or seek(0) before reading again.

How to answer Text File Read and Write Programs questions

Follow these steps for any 3-mark text file program.

  1. 1Write the function header exactly as the question names it.
  2. 2Open the file in the right mode: 'r' to read, 'w' to create or overwrite, 'a' to add at the end (use with, or remember close()).
  3. 3Choose the reading style: for line in f for line-based tasks, read() for character counts, read().split() for word tasks.
  4. 4Inside the loop apply the condition (first letter, contains a digit, word equals ...), using strip() or lower() as needed.
  5. 5Keep a counter or print the matching line; print the result after the loop.
  6. 6Close the file (not needed inside with) and call the function if the question asks for it.
  7. 7For output questions, write the file contents with a visible \n at each line end and track the pointer through every read.

Text File Read and Write Programs in real life

The idea, met in an everyday situation. Answer the question in your own words, then compare with the model answer. The one-line hook is what to remember.

Appending to a log

Suppose a school gate app writes each late arrival to late.txt. On Monday it records Asha and Ravi; on Tuesday it must add Joy without losing Monday's names.

Which mode should each day use? Write the code and show the file's contents at the end.

Try it first, then show the solutionSolution
  1. The first write can use 'w' (new file); later days must use 'a', because 'w' would erase earlier names.
  2. with open('late.txt', 'w') as f:
        f.writelines(['Asha\n', 'Ravi\n'])
    with open('late.txt', 'a') as f:
        f.write('Joy\n')
    with open('late.txt') as f:
        print(f.readlines())

Answer: ['Asha\n', 'Ravi\n', 'Joy\n']

Memory hook: w wipes, a adds.

Filtering lines into a new file

Imagine a student's diary.txt holds notes, and she wants every note that mentions a number (a date or a time) copied into reminders.txt.

Write the code and show how many lines are copied for a diary with the lines 'Exams start 3 March', 'No school on Sunday' and 'Bus leaves at 7'.

Try it first, then show the solutionSolution
  1. A line qualifies if any character is a digit; copy it as it is (it already ends with \n).
  2. count = 0
    with open('diary.txt') as src, open('reminders.txt', 'w') as dst:
        for line in src:
            for ch in line:
                if ch.isdigit():
                    dst.write(line)
                    count += 1
                    break
    print(count, 'lines copied')
    with open('reminders.txt') as f:
        print(f.read(), end='')

Answer: 2 lines copied
Exams start 3 March
Bus leaves at 7

Memory hook: Read from one door, write through another, and break after the first digit so a line is copied once.

Tricks to remember Text File Read and Write Programs

Short memory aids. Say each one aloud once, then use it on a question the same day.

  • read, readline, readlines = all, one, list

    read gives all as a string, readline gives one line, readlines gives a list.

    Use it when: MCQs on return types.

  • w wipes, a adds, r refuses

    w erases old content, a adds to the end, r refuses to work if the file is missing.

    Use it when: Choosing a mode.

  • write never presses Enter

    write() and writelines() never add a newline; you must type '\n' yourself.

    Use it when: Output questions after writelines().

  • The bookmark moves

    The file pointer is a bookmark: every read moves it forward, and seek(0) puts it back at page one.

    Use it when: Questions with two reads in a row.

Text File Read and Write Programs: solved examples

Ordered from board level to HOTS. Try each one before you open the solution.

Example 1: read(n), readline() and readlines() · 2 marks · Short answerBoard level

poem.txt contains two lines: 'Rain falls softly' and 'on the old roof'. Write the output:

f = open('poem.txt')
print(f.read(4))
print(f.readline(), end='')
print(f.readlines())
f.close()
Try it first, then show the solutionSolution
  1. read(4) returns 'Rain'. (½ mark)
  2. readline() continues from there and returns ' falls softly\n'; end='' avoids an extra blank line. (½ mark)
  3. readlines() returns the remaining line in a list, with its newline. (1 mark)

Answer: Rain
falls softly
['on the old roof\n']

Example 2: Lines starting with T or t · 3 marks · Short answerHarder board level

Write a function count_T() that reads story.txt and displays, and counts, the lines that begin with 'T' or 't'. story.txt has the lines: 'The Sun rose over the hills.', 'Birds sang in the trees.', 'A farmer walked 2 km to his field.', 'the day had begun.'

Try it first, then show the solutionSolution
  1. Open and loop over lines (1 mark); test the first character (1 mark); print and count (1 mark).
  2. def count_T():
        c = 0
        with open('story.txt', 'r') as f:
            for line in f:
                if line[0] in 'Tt':
                    print(line.strip())
                    c += 1
        print('Count:', c)
    count_T()

Answer: The Sun rose over the hills.
the day had begun.
Count: 2

Example 3: Counting a word · 3 marks · Short answerHarder board level

Write a function count_the() that counts how many times the word 'the' (in any case) appears as a separate word in story.txt (same file as above).

Try it first, then show the solutionSolution
  1. Read the text and split it into words (1 mark); compare each word in lower case (1 mark); return or print the count (1 mark).
  2. def count_the():
        with open('story.txt') as f:
            words = f.read().split()
        n = 0
        for w in words:
            if w.lower() == 'the':
                n += 1
        return n
    print(count_the())
  3. Words: The, the (line 1); the (line 2); the (line 4). 'trees.' and 'hills.' are not 'the'.

Answer: 4

Example 4: w, then a, then read · 2 marks · Short answerHarder board level

Predict the output:

f = open('t.txt', 'w')
n = f.write('ab\n')
f.writelines(['cd', 'ef\n'])
f.close()
f = open('t.txt', 'a')
f.write('gh')
f.close()
f = open('t.txt')
print(n, f.readlines())
f.close()
Try it first, then show the solutionSolution
  1. write returns the number of characters, 3. writelines adds 'cd' and 'ef\n' with no newline between them. (1 mark)
  2. Append mode adds 'gh' at the end, with no newline. (1 mark)

Answer: 3 ['ab\n', 'cdef\n', 'gh']

Example 5: seek() and tell() · 2 marks · Short answerHOTS / competency

poem.txt begins 'Rain falls softly'. Predict the output:

with open('poem.txt') as f:
    a = f.read(5)
    p = f.tell()
    f.seek(11)
    b = f.read(6)
    f.seek(0)
    c = f.read(4)
print(a, p, b, c, sep='|')
Try it first, then show the solutionSolution
  1. read(5) gives 'Rain ' and the pointer is at 5. (½ mark)
  2. seek(11) jumps to position 11 (R is 0, the space after 'falls' is 10), the 's' of 'softly'; read(6) gives 'softly'. (1 mark)
  3. seek(0) returns to the start; read(4) gives 'Rain'. (½ mark)

Answer: Rain |5|softly|Rain

Example 6: Case study: a class newsletter · 4 marks · Case-basedHOTS / competency

Suppose a class newsletter is stored in story.txt (the four lines above).
(i) Write a statement to count the characters in the file. (1 mark)
(ii) Write a function long_words() that displays the words longer than 5 characters (ignore the full stop). (2 marks)
(iii) Why would opening story.txt in 'w' mode by mistake be serious? (1 mark)

Try it first, then show the solutionSolution
  1. (i) print(len(open('story.txt').read())) counts every character including spaces and newlines: 108.
  2. (ii)
    print(len(open('story.txt').read()))
    def long_words():
        with open('story.txt') as f:
            for w in f.read().split():
                w = w.strip('.')
                if len(w) > 5:
                    print(w, end=' ')
    long_words()
    Only farmer and walked have more than 5 letters (field and begun have exactly 5), so the program prints: farmer walked
  3. (iii) 'w' erases the existing content as soon as the file is opened, so the newsletter would be lost.

Answer: (i) 108 (ii) farmer walked (iii) 'w' empties the file on opening, destroying the newsletter.

Where students lose marks in Text File Read and Write Programs

The slips examiners see most often, and what to write instead.

  • Mistake: Expecting writelines() to put each item on a new line

    Neither write() nor writelines() adds a newline.

    Wrong working

    f.writelines(['cd', 'ef']) → two lines

    Right working

    f.writelines(['cd\n', 'ef\n']) → two lines

    Do this: Add '\n' to each string you want on its own line.

    Usually costs: 1 mark in output questions.

  • Mistake: Opening in 'w' when the question says 'add' or 'append'

    'w' erases the existing contents.

    Wrong working

    f = open('late.txt', 'w') # to add a name

    Right working

    f = open('late.txt', 'a')

    Do this: Match the mode to the verb: read → r, add → a, create/overwrite → w.

    Usually costs: 1 mark.

  • Mistake: Printing lines with double spacing

    Each line already ends in '\n' and print() adds another.

    Wrong working

    print(line)

    Right working

    print(line.strip()) # or print(line, end='')

    Do this: Strip the newline before printing.

    Usually costs: Half a mark.

  • Mistake: Reading the file twice without seek(0)

    After read() the pointer is at the end, so a second read() returns ''.

    Wrong working

    c = len(f.read())
    w = len(f.read().split()) # 0

    Right working

    t = f.read()
    c = len(t)
    w = len(t.split())

    Do this: Read once into a variable, or call f.seek(0) before reading again.

    Usually costs: 1 mark.

Exam tips

  • Every recent sample paper has a 3-mark text file function in Section C (lines with a pattern or counting a word); practise one of each shape.
  • Use with open(...) as f: in answers; it closes the file automatically and examiners accept it fully.
  • When counting a word, split() and compare whole words; 'the' in line would also count 'there' and 'other'.
  • Call the function at the end if the question says 'write and call'.
  • In output questions, mark each \n in the file: readline() stops after it, and read(n) counts it as one character.

Practice questions on Text File Read and Write Programs

Write each answer on paper first. Open the hint only if you are stuck, and the answer only when you have finished.

  1. Q1 · 1 mark · MCQBoard level

    Which mode opens a text file to add data at the end without deleting what is already there?
    (a) 'r' (b) 'w' (c) 'a' (d) 'r+'

    Hint

    w wipes.

    Answer

    (c) 'a'

  2. Q2 · 1 mark · Very short answerBoard level

    What type of value does readlines() return?

    Hint

    All, one, list.

    Answer

    A list of strings, one per line (each including its newline).

  3. Q3 · 1 mark · Very short answerBoard level

    What happens to the contents of an existing file when it is opened in 'w' mode?

    Hint

    w wipes.

    Answer

    They are erased (the file is truncated to zero length) before writing.

  4. Q4 · 2 marks · Short answerHarder board level

    poem.txt contains 'Rain falls softly' and 'on the old roof'. Write the output:

    f = open('poem.txt')
    x = f.readline()
    y = f.read(6)
    print(len(x), y)
    f.close()
    Hint

    The first line includes its newline.

    Answer

    18 on the

  5. Q5 · 3 marks · Short answerHarder board level

    Write a function count_vowels() that reads poem.txt and returns the number of vowels in it. What does it return for the two-line poem above?

    Hint

    Loop over every character of read().

    Answer
    def count_vowels():
        n = 0
        with open('poem.txt') as f:
            for ch in f.read():
                if ch.lower() in 'aeiou':
                    n += 1
        return n
    print(count_vowels())

    Output: 9

  6. Q6 · 1 mark · Assertion-reasonHarder board level

    Assertion (A): Opening a file that does not exist in 'r+' mode raises an error.
    Reason (R): 'r+' opens an existing file for both reading and writing and does not create a new file.
    (a) Both A and R are true and R is the correct explanation of A. (b) Both A and R are true but R is not the correct explanation of A. (c) A is true but R is false. (d) A is false but R is true.

    Hint

    Which modes create files?

    Answer

    (a) Both are true and R explains A (FileNotFoundError).

  7. Q7 · 2 marks · Short answerHOTS / competency

    Predict the output:

    with open('n.txt', 'w') as f:
        for i in range(1, 4):
            f.write(str(i * i))
    with open('n.txt') as f:
        s = f.read()
    print(s, len(s), s[1:])
    Hint

    No newlines and no spaces are written.

    Answer

    149 3 49

Test your recall

Answer in your head or on paper first, then open the card. Pulling an answer out of memory makes it stick far better than re-reading.

  1. 1.What does readline() return at the end of the file?Show answer

    An empty string ''.

  2. 2.Which mode is used if no mode is given?Show answer

    'r' (read).

  3. 3.What does f.write('abc\n') return?Show answer

    4, the number of characters written.

  4. 4.What does seek(0) do?Show answer

    Moves the file pointer back to the beginning.

  5. 5.Which mode creates a file if it does not exist and keeps old data?Show answer

    'a' (or 'a+').

  6. 6.How do you count the words in a text file?Show answer

    len(f.read().split()).

Text File Read and Write Programs: frequently asked questions

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

read() returns all the remaining text as one string (or n characters with read(n)); readline() returns the next line including its newline; readlines() returns a list of all the remaining lines.

What is the difference between 'w' and 'a' mode?

Both create the file if it does not exist. 'w' erases any existing contents before writing; 'a' keeps them and writes at the end.

Why use the with statement to open a file?

with open(...) as f: closes the file automatically when the block ends, even if an error occurs, so you cannot forget close().

What is the difference between write() and writelines()?

write() takes one string; writelines() takes a list (or other sequence) of strings and writes them one after another. Neither adds newlines.

What are seek() and tell() used for?

tell() returns the current position of the file pointer; seek(n) moves the pointer to position n from the start, so you can re-read or skip part of a file.