CBSE CLASS XII – COMPUTER SCIENCE
CHAPTER 2: FILE HANDLING IN PYTHON
Complete Notebook Notes for Board Exam Preparation
2.1 Introduction to Files
File: A named location on a secondary storage media (hard disk, pen drive, etc.) where data is permanently stored
for later use.
Variables in a program are stored in RAM and lost once the program stops running. To store data permanently, we
save it in files on secondary storage.
Python programs themselves are stored as files with a .py extension.
Why Files Are Needed
• To store data permanently (unlike variables which vanish after program ends).
• To avoid entering the same data again and again.
• Organisations use files to store employee, inventory, sales data, etc.
✍ Exam Tip: A one-line definition of 'file' is a common 1-mark question. Learn it word-for-word.
2.2 Types of Files
Every file is stored on disk as a sequence of bytes (0s and 1s). There are two types of data files:
(a) Text File
• Contains human-readable characters (alphabets, numbers, symbols).
• Examples of extensions: .txt, .py, .csv, .html
• Internally stored as ASCII/Unicode values of characters, converted to readable form by a text editor.
• Each line ends with a special character called End of Line (EOL). Default EOL in Python = newline (\n).
• Values inside a line may be separated by whitespace, comma (,) or tab (\t).
(b) Binary File
• Stored as bytes but the bytes do NOT represent ASCII values of characters.
• Used for images, audio, video, compressed files, executable files, etc.
• Not human readable – opening in a text editor shows garbage values.
• Needs specific software to read/write. Even a single bit change can corrupt the file.
Text File vs Binary File
Basis Text File Binary File
Readability Human readable Not human readable
Content Stores ASCII/Unicode value of characters Stores actual binary data (0s and 1s)
representing content
EOL Each line ends with EOL character (\n) No concept of EOL
Opened by Any text editor (Notepad) Specific application software only
Examples .txt, .py, .csv Image, audio, video, .dat files
File size Usually smaller (only ASCII data) Additional data (metadata) is also stored,
Basis Text File Binary File
e.g. .docx
⚠ Common Mistake: Students often think .docx is a text file because it 'contains text'. It is actually treated as a
binary/compressed file with extra formatting metadata.
2.3 Opening and Closing a Text File
2.3.1 Opening a File – open()
Syntax:
file_object = open(file_name, access_mode)
• Returns a file object (file handle) stored in the variable file_object.
• If the file does not exist, open() creates a new empty file (only in write/append modes).
• If file is not in the current working directory, give the complete path.
Attributes of file object
• [Link] → returns True if file is closed, else False
• [Link] → returns the access mode in which the file was opened
• [Link] → returns the name of the file
File Access Modes (IMPORTANT TABLE)
Mode Description File Offset Position
r Opens file in read-only mode Beginning of file
rb Opens file in read-only + binary mode Beginning of file
r+ / +r Opens file in both read and write mode Beginning of file
w Write mode. Overwrites existing content; creates new file if not Beginning of file
present
wb+ / +wb Read, write and binary mode; overwrites/creates file Beginning of file
a Append mode; creates new file if not present End of file
a+ / +a Append and read mode; creates new file if not present End of file
Example:
myObject = open("[Link]", "a+")
# opens [Link] in append + read mode
# file object is placed at the END of the file
✍ Exam Tip: Remember: default mode of open() (when no mode is given) is 'r' (read) and text mode.
2.3.2 Closing a File – close()
Syntax:
file_object.close()
• Frees the memory/resources allocated to the file.
• Python flushes (writes) any unsaved data from buffer to the file before closing.
• If the file object is reassigned to another file, the previous file is closed automatically.
⚠ Common Mistake: Forgetting to close a file after writing may result in data not being saved properly, since data is
first written to a buffer and moved to disk only on close()/flush().
2.3.3 Opening a File Using 'with' Clause
Syntax:
with open(file_name, access_mode) as file_object:
# statements
• File is closed automatically once control comes out of the 'with' block.
• Useful because file gets closed even if an exception occurs, or if programmer forgets close().
• Provides simpler, cleaner syntax – no need to write close() explicitly.
with open("[Link]", "r+") as myObject:
content = [Link]()
# file is auto-closed here, outside the 'with' block
✍ Exam Tip: Board questions often ask: 'What is the advantage of using with clause over open()/close()?' – Write:
automatic closing of file even if exception occurs.
2.4 Writing to a Text File
To write into a file, open it in write (w) or append (a) mode.
• Write mode (w): erases old data, file pointer at beginning.
• Append mode (a): keeps old data, file pointer at end; new data added after old data.
2.4.1 write() Method
• Writes a single string into the file.
• Returns the number of characters written.
• We must manually add \n at the end of a line to move to next line.
• Numeric data must be converted to string using str() before writing.
myobject = open("[Link]", 'w')
[Link]("Hey I have started using files in Python\n")
41 # number of characters written (returned by write())
[Link]()
myobject = open("[Link]", 'w')
marks = 58
[Link](str(marks)) # converting number to string before writing
[Link]()
Explanation: write() first stores data in a buffer; the buffer's content is physically written to the file on disk only
when close() (or flush()) is called.
2.4.2 writelines() Method
• Used to write multiple strings (an iterable like list/tuple) in one go.
• Unlike write(), writelines() does NOT return number of characters written.
• Each string in the list should have \n if a new line is needed.
myobject = open("[Link]", 'w')
lines = ["Hello everyone\n", "Writing multiline strings\n", "This is the third
line"]
[Link](lines)
[Link]()
write() vs writelines()
Basis write() writelines()
Argument Takes a single string Takes an iterable (list/tuple) of strings
Return value Returns number of characters written Returns None (nothing)
Use case To write one line/string at a time To write multiple lines together
⚠ Common Mistake: Students often forget to add '\n' while writing multiple lines with write()/writelines(), causing
all text to appear joined in one line.
2.5 Reading From a Text File
Before reading, the file must be opened in 'r', 'r+', 'w+' or 'a+' mode. There are three ways to read a file:
2.5.1 read([n]) Method
• Syntax: file_object.read(n)
• Reads n bytes of data from the file.
• If no argument or a negative number is given, it reads the ENTIRE file content.
myobject = open("[Link]", 'r')
[Link](10)
'Hello ever' # reads first 10 characters
[Link]()
2.5.2 readline([n]) Method
• Reads ONE complete line at a time, ending at \n.
• Can also read n bytes, but stops at \n if reached earlier.
• If no argument/negative number given, reads one full line and returns it as a string.
• readline() returns an empty string ' ' when End Of File (EOF) is reached.
• To read the whole file line by line, readline() is used inside a loop (this is called looping/iterating over a file
object).
myobject = open("[Link]", 'r')
print([Link]())
'Hello everyone\n'
2.5.3 readlines() Method
• Reads ALL lines of file and returns them as a LIST of strings.
• Each list element ends with \n (except possibly the last line).
• To split each line into words: use split() function → returns list of words.
• To remove \n from each line without splitting into words: use splitlines().
myobject = open("[Link]", 'r')
print([Link]())
['Hello everyone\n', 'Writing multiline strings\n', 'This is the third line']
myobject = open("[Link]",'r')
d = [Link]()
for line in d:
words = [Link]() # splits line into list of words
print(words)
# Output:
# ['Hello', 'everyone']
# ['Writing', 'multiline', 'strings']
# ['This', 'is', 'the', 'third', 'line']
read() vs readline() vs readlines()
Method What it reads Return type
read(n) n bytes (or whole file if no/negative argument) String
readline(n) One line (up to n bytes or up to \n) String
readlines() All lines of the file List of strings
✍ Exam Tip: A very common 2-mark question: 'Differentiate between readline() and readlines()'. Key point:
readline() returns ONE line as a STRING; readlines() returns ALL lines as a LIST.
Program 2-1: Writing and Reading a Text File
Logic: Open file in write mode → accept string from user → write it → close file → reopen in read mode → loop
over file object to print each line → close file.
fobject = open("[Link]", "w") # creating a data file
sentence = input("Enter the contents to be written in the file: ")
[Link](sentence) # writing data to the file
[Link]() # closing the file
print("Now reading the contents of the file: ")
fobject = open("[Link]", "r")
for str in fobject: # looping over file object reads it line by line
print(str)
[Link]()
2.6 Setting Offsets in a File (Random Access)
Methods learnt so far read data sequentially. To access data randomly (jump to any position), Python provides
seek() and tell().
2.6.1 tell() Method
file_object.tell()
• Returns an integer showing the CURRENT byte position of the file object, counted from the beginning of file.
2.6.2 seek() Method
file_object.seek(offset [, reference_point])
• offset: number of bytes to move the file object.
• reference_point: position from where offset is counted:
◦ 0 – Beginning of file (default)
◦ 1 – Current position of file
◦ 2 – End of file
Example: [Link](5,0) moves file object to the 5th byte from the beginning.
Program 2-2: Application of seek() and tell()
print("Learning to move the file object")
fileobject = open("[Link]", "r+")
str = [Link]()
print(str)
print("Initial position:", [Link]())
[Link](0) # move to beginning
print("At beginning now:", [Link]())
[Link](10) # move to 10th byte
print("Position now:", [Link]())
str = [Link]()
print(str)
✍ Exam Tip: Remember default value of reference_point in seek() is 0 (beginning of file) if not specified.
2.7 Creating and Traversing a Text File
2.7.1 Creating a File and Writing Data
• open() with mode 'w' (or 'w+'): erases old content if file exists, else creates new file.
• open() with mode 'a' (or 'a+'): appends new data after old content, else creates new file.
Program 2-3: Create a Text File and Write Data
Logic: Open file in w+ mode → use a while loop to repeatedly take input from user and write() it → ask user if
more data is needed → stop when user enters 'n'.
fileobject = open("[Link]", "w+")
while True:
data = input("Enter data to save in the text file: ")
[Link](data)
ans = input("Do you wish to enter more data?(y/n): ")
if ans == 'n':
break
[Link]()
2.7.2 Traversing a File and Displaying Data
Logic: Open file in read mode → read first line with readline() → loop while the line is non-empty (i.e. not EOF) →
print and read next line → stop automatically when readline() returns empty string.
Program 2-4: Display Data from a Text File
fileobject = open("[Link]", "r")
str = [Link]()
while str:
print(str)
str = [Link]()
[Link]()
Program 2-5: Read and Write Using a Single File Object
Logic: Open file in w+ mode (both read & write) → write multiple lines using a loop → use tell() to check current
position → use seek(0) to move back to beginning → read() the entire content and display it.
fileobject = open("[Link]", "w+")
print("WRITING DATA IN THE FILE")
while True:
line = input("Enter a sentence: ")
[Link](line)
[Link]('\n')
choice = input("Do you wish to enter more data? (y/n): ")
if choice in ('n', 'N'):
break
print("Byte position:", [Link]())
[Link](0) # move back to beginning of file
print("READING DATA FROM THE FILE")
str = [Link]()
print(str)
[Link]()
✍ Exam Tip: Whenever a program needs both writing and reading using the SAME file object, remember to seek(0)
before reading – otherwise read() will return nothing since the pointer is at the end after writing!
2.8 The Pickle Module
Pickling: The process of converting (serializing) a Python object into a byte stream so it can be stored in a binary
file.
Unpickling: The reverse process (deserializing) – converting the byte stream back into the original Python object.
• Used to save the current state of Python objects (list, dictionary, tuple, etc.) permanently.
• Deals ONLY with binary files.
• Terminology: data is 'dumped' (not written) and 'loaded' (not read).
• Must import the module first: import pickle
2.8.1 dump() Method – Pickling
[Link](data_object, file_object)
• File must be opened in binary write mode 'wb'.
Program 2-6: Pickling Data
import pickle
listvalues = [1, "Geetika", 'F', 26]
fileobject = open("[Link]", "wb")
[Link](listvalues, fileobject)
[Link]()
2.8.2 load() Method – Unpickling
store_object = [Link](file_object)
• File must be opened in binary read mode 'rb'.
Program 2-7: Unpickling Data
import pickle
fileobject = open("[Link]", "rb")
objectvar = [Link](fileobject)
[Link]()
print(objectvar)
# Output: [1, 'Geetika', 'F', 26]
Program 2-8: Employee Records Using Pickle (with try-except)
Logic: Open file in append-binary ('ab') mode → take employee data in a loop → store each record as a list →
dump() each record → after writing, reopen file in 'rb' mode → use a while True loop with load() inside try-except
→ catch EOFError to know when all records have been read.
import pickle
bfile = open("[Link]", "ab")
recno = 1
while True:
eno = int(input("Employee number: "))
ename = input("Employee Name: ")
ebasic = int(input("Basic Salary: "))
allow = int(input("Allowances: "))
totsal = ebasic + allow
edata = [eno, ename, ebasic, allow, totsal]
[Link](edata, bfile)
ans = input("More records? (y/n): ")
if [Link]() == 'n':
break
[Link]()
# Reading back using try-except to handle EOFError
readrec = 1
try:
with open("[Link]", "rb") as bfile:
while True:
edata = [Link](bfile)
print(edata)
readrec += 1
except EOFError:
pass
⚠ Common Mistake: Since [Link]() has no way of knowing where the file ends, an EOFError is raised at the end.
Always enclose repeated load() calls in try...except EOFError.
dump() vs load()
Basis dump() load()
Purpose Writes (pickles) an object into a binary file Reads (unpickles) an object from a
binary file
File mode required 'wb' or 'ab' 'rb'
Syntax [Link](object, file_object) variable = [Link](file_object)
ONE-PAGE CHAPTER SUMMARY
• File = named location on secondary storage for permanent data storage.
• Two file types: Text file (human-readable, ASCII values) and Binary file (non-human-readable bytes).
• open(file_name, mode) opens a file and returns a file object; close() releases resources.
• Access modes: r, rb, r+, w, wb+, a, a+ (default = r, text mode).
• with clause auto-closes the file even if an exception occurs.
• Writing: write() writes a single string & returns chars written; writelines() writes multiple strings, returns
nothing.
• Reading: read(n) reads n bytes/whole file; readline(n) reads one line; readlines() reads all lines as a list.
• split() breaks a line into words; splitlines() removes \n and keeps whole line as one element.
• tell() returns current byte position; seek(offset, reference_point) moves file pointer
(0=beginning,1=current,2=end).
• Pickle module: used for binary files; dump() serializes (writes) an object; load() deserializes (reads) an object;
use try-except EOFError while reading multiple pickled objects.
IMPORTANT DEFINITIONS (Learn These)
File: A named location on secondary storage where data is permanently stored.
Text file: A file consisting of human-readable characters (alphabets, numbers, symbols) stored as ASCII/Unicode
values.
Binary file: A file consisting of non-human-readable bytes representing actual content like images/audio/video.
EOL (End of Line): A special character marking the end of a line in a text file; default is \n in Python.
File object / File handle: The object returned by open() that establishes a link between the program and the file,
used for reading/writing.
Buffer: Temporary memory area where data is held before being physically written to the file on disk.
Pickling: Serializing (converting) a Python object into a byte stream to store in a binary file.
Unpickling: Deserializing a byte stream back into a Python object.
EOF: End Of File – marks the point where there is no more data to read.
FREQUENTLY ASKED VIVA QUESTIONS
1. What is the default mode of open() function? – Read ('r') mode, text mode.
2. What happens if you open an existing file in 'w' mode? – Its old contents are erased.
3. Which mode positions the file pointer at the end of file? – Append mode ('a' or 'a+').
4. Why do we need to close a file? – To free system resources and ensure buffered data is saved to disk.
5. What does readline() return at EOF? – An empty string.
6. Which exception is raised by [Link]() at end of file? – EOFError.
7. Can seek() be used with text files? – Yes, but random offsets are safer/more predictable in binary files (text
file encoding can make byte counting inconsistent).
8. What is the difference between [Link]() and [Link]()? – tell() returns current position; seek() moves to a
specified position.
IMPORTANT BOARD QUESTIONS
2 Marks Questions
9. Differentiate between text file and binary file. (See table in section 2.2)
[Link] between readline() and readlines(). (See table in section 2.5)
[Link] between write() and writelines(). (See table in section 2.4)
[Link] is the use of seek() and tell() methods? Give syntax of each.
[Link] is the difference between the following: a) P = open("[Link]","r"); [Link](10) b) with
open("[Link]","r") as P: x = [Link]() Ans: In (a) only first 10 characters are read and file must be closed
manually. In (b) the ENTIRE file is read using read() and the file is closed automatically once the with block
ends.
3 Marks Questions
[Link] the file mode used and Python statement to open: (a) '[Link]' in read+write mode (b) '[Link]' in
binary write mode (c) '[Link]' in append+read mode (d) '[Link]' in binary read mode.
a) f = open("[Link]", "r+")
b) f = open("[Link]", "wb")
c) f = open("[Link]", "a+")
d) f = open("[Link]", "rb")
[Link] command(s) to append the lines 'Welcome my class', 'It is a fun place', 'You will learn and play' to
[Link].
f = open("[Link]", "a")
[Link]("Welcome my class\n")
[Link]("It is a fun place\n")
[Link]("You will learn and play\n")
[Link]()
[Link] pickling in Python. Explain serialization and deserialization of a Python object.
Ans: Pickling is the process used by the pickle module to serialize and deserialize Python objects. Serialization
(pickling) converts a Python object in memory into a stream of bytes that can be stored in a binary
file/database/sent over network, using dump(). Deserialization (unpickling) is the reverse process of converting
the byte stream back into the original Python object, using load().
5 Marks Questions (Programs)
[Link] a program to accept string/sentences from the user till the user enters 'END'. Save the data in a text file
and then display only those sentences which begin with an uppercase alphabet.
# Writing data
f = open("[Link]", "w")
while True:
line = input("Enter a sentence (or END to stop): ")
if line == 'END':
break
[Link](line + '\n')
[Link]()
# Reading and displaying sentences starting with uppercase letter
f = open("[Link]", "r")
for line in f:
if line[0].isupper():
print(line)
[Link]()
[Link] a program to enter Item No (int), Item_Name (string), Qty (int), Price (float) records in a binary file
using pickle. Accept number of records from user, then read the file and display records with Amount = Price
* Qty.
import pickle
f = open("[Link]", "wb")
n = int(input("How many records? "))
for i in range(n):
ino = int(input("Item No: "))
iname = input("Item Name: ")
qty = int(input("Quantity: "))
price = float(input("Price: "))
record = [ino, iname, qty, price]
[Link](record, f)
[Link]()
# Reading and displaying records
f = open("[Link]", "rb")
try:
while True:
rec = [Link](f)
print("Item No:", rec[0])
print("Item Name:", rec[1])
print("Quantity:", rec[2])
print("Price per item:", rec[3])
print("Amount:", rec[2] * rec[3])
print()
except EOFError:
pass
[Link]()
PREVIOUS CBSE-STYLE QUESTIONS (Practice)
[Link] is the purpose of the with clause in file handling? Rewrite the following code using the with clause.
20.A text file '[Link]' contains some text. Write a function to count the number of lines which start with an
alphabet 'A'.
[Link] a function in Python to count the number of lowercase alphabets present in a text file '[Link]'.
[Link] a binary file '[Link]' containing records (roll_no, name, marks), write a function to display
details of students who scored more than 75 marks.
[Link] between the following pairs, giving suitable examples wherever needed: (i) open() and close()
(ii) tell() and seek() (iii) read() and readline().
QUICK REVISION – KEY SYNTAX AT A GLANCE
Function Syntax
Open file file_object = open(file_name, access_mode)
Close file file_object.close()
With clause with open(file_name, mode) as file_object:
Write one string file_object.write(string)
Write multiple strings file_object.writelines(list_of_strings)
Read n bytes / whole file file_object.read(n)
Read one line file_object.readline(n)
Read all lines as list file_object.readlines()
Current position file_object.tell()
Move file pointer file_object.seek(offset, reference_point)
Pickle – write object [Link](object, file_object)
Pickle – read object variable = [Link](file_object)
✍ Exam Tip: Before the exam, revise this syntax table once – most 1 and 2 mark questions are directly based on
these lines!