File Handling in Python Class 12 Notes: Modes, Methods and Pickle

This page is the revision companion for File Handling in Python, Class 12 Computer Science (NCERT Chapter 2). It follows the 2026-27 session and the rationalised NCERT textbook (pages 19–38).

Everything you need to revise the chapter in one pass is here: why files exist, text versus binary files, every file open mode, the write and read methods, tell() and seek(), and the pickle module for saving whole Python objects.

Read it top to bottom once, then jump anywhere using the contents below. Each section names the textbook page it comes from, so you can open the original explanation or program whenever you want more detail.

Chapter 2 at a Glance: Files, Modes, Methods and Pickle

The chapter is one continuous build-up: first you need a reason to use files, then you meet the two kinds of files, then you learn how to open, write, read and move inside a file, and finally how to store whole objects with pickle. The table below shows where each idea lives in the book.

Chapter block What it gives you Textbook pages
Introduction to files Why programs need permanent storage, and what a file is 19–20
Types of files Text vs binary files, EOL, how characters are encoded as bytes 20–21
Opening and closing a text file open(), access modes, file attributes, close(), the with clause 21–23
Writing to a text file write() and writelines() 23–25
Reading from a text file read(), readline(), readlines(), split() and splitlines() 25–27
Setting offsets in a file tell() and seek() for random access 28–29
Creating and traversing a text file Complete programs that create, write, display and re-read data 29–31
The pickle module dump(), load(), EOFError handling for binary files 32–35
Summary and exercises Chapter recap and the exercise set 35–38

So the logic runs: variables do not survive a program run, and data must live in files; a file is either text or binary; you open it in a chosen access mode, transfer data with the read/write methods, reposition with tell()/seek(), and use pickle when the data is a Python object.

The rest of the Class 12 Computer Science notes on this site follow the same style, and you can browse the Class 12 revision notes hub or search the CBSE notes library for other subjects — the Queue chapter notes, for example, use the same method-by-method format.

Every page reference here can be checked in the official Rationalised NCERT Class 12 Computer Science PDF hosted by NCERT, which also contains the original programs if you want to compare your own code.

Text Files vs Binary Files: What Is Actually Stored

Variables in a program live only while the program runs: input and output disappear when execution ends (NCERT, p. 19). Organisations keep employee, inventory and sales records permanently on secondary storage so the same data never has to be typed twice, and files are how that data is held.

A file is a named location on a secondary storage medium where data are stored permanently for later access (NCERT, p. 20). One everyday use: a game can save the high score and settings (sound on/off, difficulty) into a small text file when it closes, then read them back the next time it runs.

Without the file, that state is gone the moment the program exits.

Point of comparison Text file Binary file
What the bytes represent Characters — alphabets, numbers, symbols — encoded with ASCII, UNICODE or another scheme; each byte stands for one character in that encoding Actual content such as image, audio, video, executable or compressed data; the bytes are not ASCII character codes
Human readability Readable; opens in any text editor Not human readable; a text editor shows garbage values
Software needed A simple text editor such as Notepad Specific programs are required to access the contents
Examples .txt, .py, .csv Images, audio, video, executables, compressed files
Corruption behaviour Errors are comparatively easy to spot and fix A single bit change can corrupt the file; errors are hard to remove because the contents cannot be read by a human
Line structure Each line ends with an End of Line (EOL) character A continuous stream of bytes — no concept of lines

The .docx mystery, solved. In Activity 2.1 the book asks you to save your name as a .txt and as a .docx; the .txt measures in bytes while the .docx measures in KB (NCERT, p. 20).

The reason: the .txt stores only the characters you typed, but the .docx stores those same characters plus metadata — the author’s name, page settings, font type and size, and the dates of creation and modification. That extra information is the size difference.

There is a second, subtler misconception hiding here. A text file does not store readable characters directly. It stores byte values — the ASCII value 65 is stored as its binary equivalent, and the editor decodes it and displays ‘A’ (NCERT, p. 20). What you see in Notepad is the editor’s translation, not the file’s raw contents.

Every line of a text file is terminated by a special End of Line (EOL) character. Python’s default EOL is the newline \n; other characters can mark the EOL, and an editor starts a new display line wherever it meets one (NCERT, p. 20).

File Handling Glossary: Terms You Must Know

These are the words you will be expected to define and use in answers. The meanings below are reworded for quick recall.

Term Meaning Example
File A named location on secondary storage where data are permanently kept for later access ‘marks.txt’
Text file A sequence of characters (alphabets, numbers, symbols); each character is stored as bytes in some encoding .txt, .py, .csv
Binary file A stream of bytes that represent content such as images or audio — not character codes Image, audio, video, executable
EOL End of Line; the special character that terminates each line of a text file \n in Python
File object / file handle The object returned by open(); it links the program to the file and carries out every read and write f in f = open(‘a.txt’, ‘r’)
Access mode The operation a file is opened for — reading, writing, appending, and whether both reading and writing are allowed ‘r’, ‘w’, ‘a’, ‘r+’, ‘rb’
File offset The position of the file object inside the file, counted in bytes from the start Position 10 after seek(10)
Serialization / pickling Converting an in-memory Python object into a stream of bytes Saving a list to a binary file
Deserialization / unpickling Converting a byte stream back into a Python object Loading that list back into memory

Opening and Closing Files: Access Modes and Offsets

Python’s io module provides the functions used for file handling (NCERT, p. 21). To open a file:

file_object = open(file_name, access_mode)

open() returns the file object, also called the file handle. Every later read or write goes through this handle. If the named file does not exist, open() creates a new empty file with that name; if the file is not in the current working directory, file_name must carry the complete path (NCERT, p. 22).

The handle exposes three attributes: file.closed (True when the file is closed, False otherwise), file.mode (the access mode used) and file.name (the file’s name) (NCERT, pp. 21–22).

File mode What it does File offset when opened
r Read only (the default mode) Beginning of the file
rb Read only, in binary mode Beginning of the file
r+ or +r Both read and write Beginning of the file
w Write; overwrites the file if it exists, or creates a new one Beginning of the file
wb+ or +wb Read, write and binary; overwrites an existing file, or creates a new one Beginning of the file
a Append; new data goes after existing data; creates the file if missing End of the file
a+ or +a Append and read; creates the file if missing End of the file

Three switches build every mode: r/w/a picks the operation (read; write with overwrite; append at the end), b switches to binary, and + allows both reading and writing. The default mode is read and the default file type is text (NCERT, p. 22).

Activity 2.2 lists rb+, wb, w+, ab, ab+ — you can derive each from these switches, and the offsets follow the same rule: the w family starts at the beginning, the a family at the end.

close() closes the file. While closing, the system frees the memory and other resources allocated to the file, and Python flushes any unwritten data still in the buffer to the file first. If the file object is re-assigned to another file, the previous file is closed automatically (NCERT, p. 23).

The with clause closes the file for you:

with open(‘myfile.txt’, ‘r+’) as myObject:

Once control leaves the with block, the file is closed automatically — even if an exception occurs — and the syntax is simpler because no explicit close() is needed (NCERT, p. 23).

Writing to a Text File: write() and writelines()

Before writing, open the file in write or append mode. In ‘w’ mode an existing file is erased and the object is placed at the beginning; in ‘a’ mode new data is added after the old data, because the object is already at the end (NCERT, pp. 23–24).

For a newly created file the two modes are equivalent: the file is empty, so both start writing from the beginning.

write() takes exactly one string, writes it to the file, and returns the number of characters written in that single call (NCERT, p. 24). Three rules to remember:

  • You must add the newline yourself — a sentence written without \n glues itself to whatever is written next.
  • The newline ‘\n’ counts as a single character inside the returned count.
  • Numeric data must be converted with str() before calling write(), because the argument must be a string.

Data does not reach the disk instantly. write() places data into a buffer; the buffer moves into the file when close() runs, and flush() forces the buffered contents to the file whenever you need it updated immediately (NCERT, p. 24).

writelines() takes an iterable of strings — a list, tuple or similar — and writes them all (NCERT, pp. 24–25). Two differences from write():

  • It returns nothing (no character count).
  • It does not add newlines — each string must carry its own ‘\n’ if you want separate lines.

Activity 2.3 asks you to swap writelines() for write(); the predictable result is an error, because write() accepts only a single string, not a list.

Reading from a Text File: read(), readline() and readlines()

Before reading, the file must be opened in ‘r’, ‘r+’, ‘w+’ or ‘a+’ mode (NCERT, p. 25). The three reading methods behave as follows.

Method Behaviour Return value
read([n]) Reads n bytes from the current position; with no argument (or a negative number) it reads the entire file One string
readline([n]) Reads one complete line up to the newline; with n, it reads up to n bytes but never beyond the \n One string; a newline is included only when a whole line is read; ” at EOF
readlines() Reads all remaining lines A list of strings, with the newline kept on lines that had it

The empty string at EOF is what makes line-by-line loops possible. The standard pattern from Program 2-4 reads one line, uses it, and repeats:

str = fileobject.readline() while str:

    print(str)     str = fileobject.readline()

An empty string is falsy, so the loop ends naturally at the end of the file (NCERT, p. 30). You can also loop over the file object itself — for line in file_object: — as Program 2-1 does, because a file object is iterable line by line (NCERT, p. 27).

Once you have lines from readlines(), split() and splitlines() give different breakdowns (NCERT, pp. 26–27). For an original sample line, ‘Python for Class 12’:

  • line.split() → [‘Python’, ‘for’, ‘Class’, ’12’] — each word becomes a list element.
  • line.splitlines() → [‘Python for Class 12’] — the whole line stays one element.

Moving Inside a File: tell() and seek()

The methods so far read files sequentially. tell() and seek() give random access: you ask where the file object currently is, then you move it somewhere else (NCERT, p. 28).

tell() returns the current position of the file object as a byte count from the beginning of the file. The position is an integer; the syntax is file_object.tell() (NCERT, p. 28).

seek(offset, reference_point) moves the file object by offset bytes, counted from a reference point. The reference point can be:

  • 0 — the beginning of the file (this is the default)
  • 1 — the current position of the file object
  • 2 — the end of the file

So fileObject.seek(5, 0) places the object at the 5th byte from the start (NCERT, p. 28).

One caution about text files. seek() counts bytes, and a single character in a text file can occupy more than one byte depending on the encoding used. An arbitrary byte jump in a text file can therefore land mid-character and give unreliable results.

The safe habit is to save a known-good position with tell() and later seek() back to that same number — a position that actually held the file object is always valid.

Creating and Traversing a Text File: Loop Patterns

The chapter puts the methods together in three program patterns (NCERT, pp. 29–31).

Pattern 1 — create a file from user input (Program 2-3). Open in ‘w+’ mode, then keep accepting input until the user says ‘n’:

fileobject = open(“practice.txt”, “w+”) while True:

    data = input(“Enter data to save in the text file: “)     fileobject.write(data)     ans = input(“Do you wish to enter more data? (y/n): “)     if ans == ‘n’: break fileobject.close()

Notice what this program does not do: it never writes ‘\n’. That is why the later output shows ‘Computer SciencePython’ — one input ends ‘…Computer Science’ and the next begins ‘Python…’, and with no newline between them the lines run together (NCERT, pp. 30–31).

Pattern 2 — display the file line by line (Program 2-4). Open in ‘r’ mode and loop with readline():

fileobject = open(“practice.txt”, “r”) str = fileobject.readline() while str:

    print(str)     str = fileobject.readline() fileobject.close()

The loop depends on readline() returning an empty string at EOF to stop (NCERT, p. 30).

Pattern 3 — one file object writes and then reads (Program 2-5). Since both operations use a single object, the file is opened in ‘w+’ mode. After writing every line (explicitly adding ‘\n’), the program prints tell(), then calls seek(0), and only then reads:

fileobject = open(‘report.txt’, ‘w+’) # … write lines with fileobject.write(line + ‘\n’) …

print(‘The byte position of file object is ‘, fileobject.tell()) fileobject.seek(0) str = fileobject.read() print(str) fileobject.close()

This pattern matters because after writing, the file object sits at the end of the file. Without seek(0), a following read() would start from the end and return nothing (NCERT, p. 31).

The Pickle Module: dump(), load() and EOFError

Everything in Python is an object — lists, tuples and dictionaries included. Sometimes a program must save the current state of its variables so it can restore them later; NCERT’s own example is a video game saving the current level or stage and the player’s score (NCERT, p. 32).

Pickle is the module used for serializing (pickling) and de-serializing (unpickling) any Python object structure (NCERT, p. 32).

  • Serialization / pickling: converting an object in memory (RAM) into a stream of bytes (a byte stream) that can be stored in a file on disk, kept in a database, or sent across a network.
  • De-serialization / unpickling: the inverse — converting that byte stream back into a Python object.

Pickle works with binary files, and its vocabulary is different: you do not ‘write’ or ‘read’ data, you dump and load it, and you must import the pickle module first (NCERT, p. 32).

dump(data_object, file_object) pickles one object into a binary file that must be opened in ‘wb’ mode (NCERT, p. 32).

store_object = load(file_object) unpickles one object from a binary file opened in ‘rb’ mode and stores it in the new variable (NCERT, p. 33).

To read many records, call load() repeatedly inside a while loop. When load() is called past the last record, it raises EOFError, so the standard pattern guards the loop with try/except EOFError (NCERT, p. 34).

Program 2-8 also shows a useful trick: after writing records into a file opened in ‘ab’ mode, calling bfile.tell() reports the current byte position, which equals the size of the binary file in bytes (NCERT, p. 34). Each employee record is stored as a list, so reading the file back produces one list per record.

File Handling Syntax Cheat Sheet

One table of every method in the chapter — syntax, behaviour, return value and where it appears in the textbook.

Method / syntax What it does Returns / notes NCERT page
open(file_name, access_mode) Opens (or creates) the file and returns the handle File object; default mode is ‘r’ 21
file_object.close() Closes the file, frees resources, flushes buffered data Nothing 23
with open(…) as file_object: Opens the file and auto-closes it outside the block Simpler and safer than manual close() 23
file_object.write(string) Writes one string Number of characters written 24
file_object.writelines(iterable) Writes an iterable of strings Nothing; no automatic newlines 24
file_object.read([n]) Reads n bytes; the whole file if no argument One string 25
file_object.readline([n]) Reads one line, up to the newline One string; ” at end of file 26
file_object.readlines() Reads all remaining lines A list of strings with ‘\n’ kept 26
file_object.tell() Reports the byte position from the start An integer 28
file_object.seek(offset, ref=0) Moves the file object by offset bytes from ref (0, 1 or 2) Nothing; ref defaults to 0 28
pickle.dump(data_object, file_object) Pickles one object into a binary file (‘wb’) Nothing 32
pickle.load(file_object) Unpickles one object from a binary file (‘rb’) The stored object; raises EOFError past the last record 33

Worked Examples: Byte Positions and Pickle Records

Example 1: Where is the file object?

The file notes.txt contains exactly one line — ‘Exam Ready\n’, which is 11 bytes. The method is: read some bytes, check tell(), jump with seek(), then read the rest.

f = open(‘notes.txt’, ‘r+’) print(f.read(4)) print(f.tell()) f.seek(5) print(f.read()) f.seek(0) print(f.tell()) f.close()

Output:

Exam 4 Ready 0

Step 1: read(4) takes bytes 0–3 (positions: 0 E, 1 x, 2 a, 3 m), so the object now sits after 4 bytes and tell() reports 4.

Step 2: seek(5) positions the object at byte 5, which is the ‘R’ of ‘Ready’ (position 4 holds the space).

Step 3: read() with no argument runs from position 5 to the end of the file, so it returns ‘Ready\n’.

Step 4: seek(0) resets the object to the start; tell() reports 0, and a fresh read() would recover the whole line ‘Exam Ready\n’.

For completeness: after a full read(), the object rests at byte 11 — the end of the 11-byte file.

Example 2: Pickling three student records

Three student records — [101, ‘Ananya’, 88], [102, ‘Rahul’, 76] and [103, ‘Meera’, 93] — are dumped to student.dat in ‘wb’ mode, then loaded back in ‘rb’ mode until EOFError ends the loop.

import pickle students = [[101, ‘Ananya’, 88], [102, ‘Rahul’, 76], [103, ‘Meera’, 93]] with open(‘student.dat’, ‘wb’) as bf:

    for s in students:

        pickle.dump(s, bf) with open(‘student.dat’, ‘rb’) as bf:

    while True:

        try:

            rec = pickle.load(bf)             print(rec)         except EOFError:

            break

Output:

[101, ‘Ananya’, 88] [102, ‘Rahul’, 76] [103, ‘Meera’, 93]

Each dump() call appends one pickled object to the file, so the three load() calls retrieve the records in the same order they were saved. The while True loop has no exit condition of its own — the EOFError raised after the third record is what ends it, and the except clause exits quietly.

Common Mistakes in File Handling and Their Fixes

Students write X Correct is Y Why
myfile.write(58) myfile.write(str(58)) write() accepts only a string; numeric data must be converted to a string before writing (NCERT, p. 24)
open(‘data.txt’, ‘w’) to add data to an existing file Use ‘a’ (append) ‘w’ wipes all existing contents; ‘a’ keeps old data and writes after it
myfile.writelines([‘a’, ‘b’]) expecting ‘a\nb\n’ Include ‘\n’ inside each string yourself writelines() joins the strings exactly as given and returns nothing (NCERT, p. 24)
if myfile.readline() is None, stop Check for the empty string ” readline() returns ” at EOF, never None; the empty string is what makes while str: loops stop (NCERT, p. 26)
Open ‘a+’ and call read() straight away Call seek(0) before reading In append modes the file object starts at the end, so a read from the current position returns ” (NCERT, p. 22)
Call pickle.load() in a loop without a guard Wrap the call in try/except EOFError load() raises EOFError once it runs past the last record; the exception ends the loop cleanly (NCERT, p. 34)
Assuming a text file stores readable characters It stores byte values that the editor decodes ASCII value 65 is stored as its byte equivalent and displayed as ‘A’ by the editor (NCERT, p. 20)

How to Write Complete Answers to the Textbook Exercises

This section gives the shape a complete answer should take for each type of question in the exercises (NCERT, pp. 37–38) — not the solutions themselves.

  • Differentiate questions (text vs binary, readline vs readlines, write vs writelines): answer as a two-column table or paired bullets. Each difference must name a real property — what the contents represent, what software can open them, or what the method returns — not a vague “they are different”.
  • Use and syntax questions (open, read, seek, dump): give the purpose in one sentence, the exact syntax, and a one-line example that shows the method working.
  • File mode questions: name the mode, write the complete open() statement with the quoted file name, and state the file offset the mode produces — beginning or end of the file.
  • Why close a file: a complete answer covers three points — the system frees the memory and resources attached to the file; buffered, unsaved data is flushed to the file when it closes; and a file left unclosed risks losing data (NCERT, p. 23).
  • Statement-comparison questions (plain open vs with): say what each statement returns, then explain what the with clause guarantees — automatic closing even when an exception interrupts the block (NCERT, p. 23).
  • Program-writing questions: write complete, runnable code. For text files, close() after writing (or use with) and add ‘\n’ wherever a line break is wanted. For pickle files, import pickle, open in ‘wb’/’ab’ mode for dumping and ‘rb’ for loading, and guard load() with try/except EOFError.
  • Record-based binary program: build each record as a Python list, dump it inside the input loop, and compute derived fields such as the amount before displaying so the output is complete.

Last-Minute Recap: File Handling Checklist

Run through this list the night before your test. If you can tick every item, you have the chapter covered.

  • I can define a file and a file handle, and I can explain why programs need permanent storage.
  • I can tell text and binary files apart — contents, readability, tools, examples and corruption behaviour.
  • I know the open modes shown in the table (r, rb, r+, w, wb+, a, a+) and where the file object starts in each.
  • I can use write() (one string, returns the character count, needs \n) and writelines() (iterable of strings, no automatic newlines).
  • I can use read() (n bytes or everything), readline() (one line; ” at EOF) and readlines() (a list of lines).
  • I can locate the file object with tell() and move it with seek(), and I know why arbitrary jumps in text files are risky.
  • I can dump() objects to a binary file and load() them back, handling EOFError with try/except.
  • I can write a loop that reads a file line by line, and I remember that readline() returns ” — not None — at EOF.
  • I know that append modes start the object at the end, so ‘a+’ needs seek(0) before reading.

Memory device for modes: r = read, w = write and wipe, a = append and add, + = both read and write.

File Handling Doubts, Answered

Why does readline() return an empty string when the file ends?

Because the empty string is readline()’s way of signalling the end of the file (NCERT, p. 26). The value ” is falsy, so a while str: loop simply stops. It never returns None — checking for None is the classic confusion.

Should I use ‘w’ or ‘a’ when I want to add data to an existing file?

Use ‘a’ (append). The ‘w’ mode erases all existing contents and then writes, so you would lose the old data. Append mode keeps the existing data and adds the new data after it. Only for a brand-new file do the two behave the same, because there is nothing to overwrite or append to.

Does writelines() add a newline after every string?

No. writelines() joins the strings exactly as you pass them — no newline is inserted anywhere. If you want each string on its own line, you must include the ‘\n’ at the end of each string yourself (NCERT, p. 24).

Why do I get EOFError while loading a pickle file, and how do I handle it?

pickle.load() raises EOFError when it is called past the last record in the file — the file position has reached the end. The standard fix is to put load() inside a try block and catch EOFError with except, letting the loop stop quietly instead of crashing (NCERT, p. 34).

Why should I use with open() instead of open() and close()?

Because the with clause closes the file automatically once control leaves the block, even if an exception occurs midway. You cannot forget to close the file, and the syntax is simpler — no separate close() line is needed (NCERT, p. 23).

Can I write numbers directly to a text file with write()?

No. write() requires a string argument, so a number must be converted first — myfile.write(str(58)). Passing an integer produces an error because the argument is not a string (NCERT, p. 24).

Reference: NCERT Class 12 Computer Science textbook, chapter File Handling in Python.

Explore Class 12 Computer Science Notes

  • Next: Queue

Class 12 Computer Science on LearnCBSE:

Related chapters:

  • Sorting notes
  • Searching notes
  • Understanding Data notes


Related

More from this section