Chapter 2
File Handling in Python
Class XII Computer Science — Detailed Study Notes
💡 Key Point
A file is a named location on secondary storage media where data are permanently
stored for later access.
Why Do We Need Files?
• Permanent storage: Data survives after the program exits.
• Reusability: Stored data can be used in future runs without re-entering it.
• Large data handling: Files can store much more data than variables in RAM.
• Sharing: Files can be shared between different programs or users.
• Organisation: Related data (employee records, sales, inventory) can be stored together.
📌 Real-World Example
An organisation wants to permanently store employee details like name, salary, and
department. Re-entering this data every time is impractical. Instead, it is stored in files
once and read whenever needed.
2.2 Types of Files
Every file stored on a computer is ultimately a collection of 0s and 1s (binary form) — a series of bytes
stored one after another. There are two main categories:
Text File Binary File
Consists of human-readable characters Contains non-human-readable bytes (raw data)
(alphabets, digits, symbols)
Can be opened and read by any text editor Requires specific software to read/write
(Notepad, VS Code)
Stores ASCII/Unicode values of characters Stores actual content: images, audio, video,
executables
Examples: .txt, .py, .csv, .html Examples: .jpg, .mp3, .exe, .dat, .docx
Text File Binary File
Lines terminated by EOL character (\n by A single-bit change can corrupt the file
default)
2.2.1 Text Files
A text file stores data as a sequence of characters — alphabets, numbers, and special symbols.
Internally, each character is stored as its ASCII or Unicode value (a sequence of bytes).
When you open a text file using a text editor like Notepad, the editor translates each ASCII/Unicode
value back into the readable character. For example:
Character ASCII Value Binary Equivalent
A 65 01000001
B 66 01000010
a 97 01100001
0 (digit) 48 00110000
End of Line (EOL): Each line in a text file ends with a special character. In Python, the default EOL is
\n (newline). When a program encounters this character, it moves to a new line.
Separators in text files: Values are commonly separated by whitespace, comma (,), or tab (\t). This is
used in CSV files.
📌 Difference Between .txt and .docx
A .txt file contains only the ASCII equivalent of the text content. A .docx file contains the
text plus metadata: author name, page settings, font type and size, date of creation, etc.
That is why a .docx file is always larger in size than a .txt file with the same text.
2.2.2 Binary Files
Binary files also store data as bytes (0s and 1s), but unlike text files, these bytes do NOT represent
ASCII values of characters. Instead, they represent actual content such as:
• Image data (pixels) in .jpg, .png files
• Audio data in .mp3, .wav files
• Video data in .mp4 files
• Compressed data in .zip files
• Executable code in .exe files
Not human-readable: Opening a binary file in a text editor shows garbage/junk values because the
bytes are not ASCII characters.
✅ Remember
Binary files are very fragile — even a single-bit change can corrupt the file and make it
unreadable by the supporting application. We need specific software (like media players,
image viewers) to correctly read binary files.
2.3 Opening and Closing a Text File
Before performing any read or write operation on a file, we must first open it. Python provides the built-
in io module with functions to handle files. The most important function is open().
2.3.1 Opening a File — The open() Function
Syntax:
file_object = open(file_name, access_mode)
file_name — The name (and path if needed) of the file to open.
access_mode — Optional. Specifies the mode in which the file is opened (read, write, append, etc.).
Default is read mode ('r').
file_object — The returned file handle used to read/write data. It acts as a link between the program
and the file on disk.
File Attributes
The file object has the following useful attributes:
• [Link] — Returns True if the file is closed, False otherwise.
• [Link] — Returns the access mode in which the file was opened.
• [Link] — Returns the name of the file.
File Open Modes (Table 2.1)
Mode Description File Offset
Position
r Opens file in read-only mode. File must exist. Beginning of file
Mode Description File Offset
Position
rb Opens file in binary and read-only mode. Beginning of file
r+ or +r Opens file for both reading and writing. Beginning of file
w Opens file in write mode. Overwrites existing content. Beginning of file
Creates new file if not exists.
wb+ or +wb Opens file in read, write and binary mode. Overwrites Beginning of file
existing. Creates if not exists.
a Opens file in append mode. New data is added at end. End of file
Creates file if not exists.
a+ or +a Opens file in append and read mode. Creates file if not End of file
exists.
📌 Important
If access_mode is not specified, the file opens in 'r' (read) mode by default. Text mode is
default. For binary files, add 'b' to the mode, e.g., 'rb', 'wb'.
Example: Opening a File
# Open [Link] in append+read mode
myObject = open("[Link]", "a+")
# Check file attributes
print([Link]) # Output: [Link]
print([Link]) # Output: a+
print([Link]) # Output: False
Output:
[Link]
a+
False
2.3.2 Closing a File — The close() Method
Once all read/write operations are complete, it is good practice to close the file using close().
file_object.close()
Why close a file?
• Frees the memory allocated to the file object.
• Ensures any unwritten (buffered) data is flushed (written) to the file.
• Prevents data corruption from incomplete writes.
• Releases the file so other programs can access it.
📌 Auto-close
If the file object is re-assigned to another file, Python automatically closes the previous
file. However, it is always recommended to explicitly close files.
2.3.3 Opening a File Using with Clause
Python provides a cleaner way to handle files using the with statement. This is the recommended
approach for file handling as it automatically closes the file when the block ends.
Syntax:
with open(file_name, access_mode) as file_object:
# file operations here
...
Example:
with open("[Link]", "r+") as myObject:
content = [Link]()
print(content)
# File is automatically closed here — no need to call close()
✅ Remember
Advantages of with clause: • File is closed automatically — even if an exception (error)
occurs. • Simpler, cleaner syntax. • Prevents resource leaks. • Best practice in Python
file handling.
2.4 Writing to a Text File
To write data to a file, open it in write mode ('w') or append mode ('a'). Python provides two methods
for writing:
• write() — Writes a single string to the file.
• writelines() — Writes a sequence (list, tuple) of strings to the file.
2.4.1 The write() Method
The write() method takes a string as argument and writes it to the file. It returns the number of
characters written.
Syntax:
file_object.write(string)
Important: You must manually add \n at the end of each line — write() does NOT add a newline
automatically.
Important: If you write numeric data, convert it to string first using str() .
Example 1 — Writing a String
myobject = open("[Link]", 'w')
[Link]("Hey I have started #using files in Python\n")
# 41 is returned — length of the string including \n
[Link]()
Output:
41
Note: The write() method returns 41 — the total number of characters (including \n treated as 1
character).
Example 2 — Writing a Number
myobject = open("[Link]", 'w')
marks = 58
# Numbers must be converted to string before writing
[Link](str(marks))
# Returns 2 (length of '58')
[Link]()
Output:
2
📌 How write() works internally
The write() method actually writes data to a buffer (temporary memory), NOT directly to
the file. When close() is called, the buffer contents are flushed (moved) to the actual file
on disk. You can also use flush() method to force-write buffer contents to the file without
closing it.
2.4.2 The writelines() Method
The writelines() method writes a sequence of strings (list, tuple, etc.) to the file. Unlike write(), it
does NOT return the character count. You must add \n manually inside each string.
Syntax:
file_object.writelines(iterable_of_strings)
Example — Using writelines()
myobject = open("[Link]", 'w')
lines = [
"Hello everyone\n",
"Writing multiline strings\n",
"This is the third line"
]
[Link](lines)
[Link]()
When [Link] is opened in Notepad, it shows:
Output:
Hello everyone
Writing multiline strings
This is the third line
✅ Remember
write() vs writelines(): • write() writes ONE string and returns character count. •
writelines() writes MULTIPLE strings (iterable) and returns None. • Neither automatically
adds a newline — you must include \n in strings. • For a newly created file, there is no
difference between write() and append() since the file is empty.
2.5 Reading from a Text File
Before reading, ensure the file is opened in "r" , "r+" , "w+" , or "a+" mode. There are three
methods to read file contents:
Method Description
read(n) Reads n bytes. Reads entire file if n is omitted or negative.
readline([n]) Reads one complete line (up to \n). Reads n bytes max if specified.
readlines() Reads all lines and returns them as a list of strings.
2.5.1 The read() Method
Reads a specified number of bytes from the file. If no argument (or negative) is given, the entire file is
read.
Syntax:
file_object.read(n) # reads n bytes
file_object.read() # reads entire file
Example 1 — Read 10 bytes
myobject = open("[Link]", 'r')
print([Link](10))
[Link]()
Output:
Hello ever
Note: Reads first 10 characters: 'Hello ever' (from 'Hello everyone...')
Example 2 — Read entire file
myobject = open("[Link]", 'r')
print([Link]())
[Link]()
Output:
Hello everyone
Writing multiline strings
This is the third line
2.5.2 The readline([n]) Method
Reads one complete line at a time (up to the newline character \n). If n is specified, reads at most n
bytes from the current line.
file_object.readline() # reads one full line
file_object.readline(n) # reads up to n bytes of current line
Example 1 — Read first 10 bytes of first line
myobject = open("[Link]", 'r')
print([Link](10))
[Link]()
Output:
Hello ever
Example 2 — Read entire first line
myobject = open("[Link]", 'r')
print([Link]())
[Link]()
Output:
Hello everyone\n
Example 3 — Loop through all lines
myobject = open("[Link]", 'r')
line = [Link]()
while line: # empty string '' means EOF
print(line, end='') # end='' avoids double newline
line = [Link]()
[Link]()
Output:
Hello everyone
Writing multiline strings
This is the third line
📌 End of File (EOF)
When readline() reaches the end of the file, it returns an empty string '' (not None). This
is used as the loop-termination condition.
2.5.3 The readlines() Method
Reads ALL lines from the file and returns them as a list of strings. Each list element is one line,
ending with \n (except possibly the last line).
file_object.readlines()
Example — Using readlines()
myobject = open("[Link]", 'r')
print([Link]())
[Link]()
Output:
['Hello everyone\n', 'Writing multiline strings\n', 'This is the third
line']
Note: Each element ends with \n except the last line.
Using split() and splitlines() with readlines()
split() — splits each line into individual words (by whitespace):
myobject = open("[Link]", 'r')
d = [Link]()
for line in d:
words = [Link]()
print(words)
[Link]()
Output:
['Hello', 'everyone']
['Writing', 'multiline', 'strings']
['This', 'is', 'the', 'third', 'line']
splitlines() — returns each complete line (without \n) as a list element:
for line in d:
words = [Link]()
print(words)
Output:
['Hello everyone']
['Writing multiline strings']
['This is the third line']
Program 2-1: Write then Read a Text File
# Writing to file
fobject = open("[Link]", "w") # Create/open in write mode
sentence = input("Enter contents for file: ")
[Link](sentence) # Write data
[Link]() # Close file
# Reading from file
print("Now reading the contents of the file:")
fobject = open("[Link]", "r") # Open in read mode
for line in fobject: # Loop over file object
print(line)
[Link]()
Output:
Enter contents for file: roll_numbers = [1, 2, 3, 4, 5, 6]
Now reading the contents of the file:
roll_numbers = [1, 2, 3, 4, 5, 6]
2.6 Setting Offsets in a File
So far, we have read files sequentially — from beginning to end. Python also allows random access
to file data using seek() and tell() .
2.6.1 The tell() Method
Returns an integer specifying the current position of the file object (number of bytes from the
beginning of the file).
file_object.tell()
Example
myobject = open("[Link]", 'r')
print([Link]()) # At start: position 0
[Link](5) # Read 5 bytes
print([Link]()) # Now at position 5
[Link]()
Output:
0
5
2.6.2 The seek() Method
Moves (repositions) the file object to a specific location in the file.
file_object.seek(offset [, reference_point])
offset — Number of bytes to move the file object.
reference_point — Starting point from which offset is counted:
Value Meaning
0 (default) Beginning of the file
1 Current position of the file object
2 End of the file
Examples
[Link](5, 0) # Move to byte 5 from beginning
[Link](3, 1) # Move 3 bytes forward from current position
[Link](0) # Go back to beginning of file (default
reference=0)
Program 2-2: Application of seek() and tell()
print("Learning to move the file object")
fileobject = open("[Link]", "r+")
str = [Link]() # Read entire file
print(str)
print("Initially position:", [Link]())
[Link](0) # Move to beginning
print("After seek(0):", [Link]())
[Link](10) # Move to 10th byte
print("After seek(10):", [Link]())
str = [Link]() # Read from position 10
print(str)
[Link]()
Output:
Learning to move the file object
roll_numbers = [1, 2, 3, 4, 5, 6]
Initially position: 33
After seek(0): 0
After seek(10): 10
rs = [1, 2, 3, 4, 5, 6]
📌 seek() in Text vs Binary Files
In text mode, seek() works reliably only with reference_point=0 (beginning of file). For
reference_point=1 or 2, binary mode ('rb') must be used.
2.7 Creating and Traversing a Text File
Now let us apply everything we have learnt to perform real-world file operations on a text file called
[Link].
2.7.1 Creating a File and Writing Data
We use open() with write or append mode:
• Write mode (w): If file exists, all content is erased. If not, a new empty file is created.
• Append mode (a): New data is added after existing data. File is created if it doesn't exist.
Program 2-3: Create a Text File and Write Data
# Program to create a text file and add data
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]()
Output:
Enter data to save in the text file: I am interested to learn about
Computer Science
Do you wish to enter more data? (y/n): y
Enter data to save in the text file: Python is easy to learn
Do you wish to enter more data? (y/n): n
2.7.2 Traversing a File and Displaying Data
To read and display data, open the file in read mode and use readline() in a loop.
Program 2-4: Display Data from a Text File
fileobject = open("[Link]", "r")
str = [Link]() # Read first line
while str: # Continue until empty string (EOF)
print(str)
str = [Link]() # Read next line
[Link]()
Output:
I am interested to learn about Computer SciencePython is easy to learn
📌 Why are lines joined?
In Program 2-3, we didn't add \n after each write. So both strings were written without a
separator. Always add \n at the end of data in write() to separate lines.
Program 2-5: Read and Write in One Program (Using w+ and seek)
fileobject = open("[Link]", "w+") # w+ allows both read and write
print("WRITING DATA IN THE FILE")
print()
while True:
line = input("Enter a sentence: ")
[Link](line)
[Link]('\n') # Add newline after each sentence
choice = input("Do you wish to enter more data? (y/n): ")
if choice in ('n','N'):
break
print("Byte position of file object:", [Link]())
[Link](0) # Move back to beginning to read
print()
print("READING DATA FROM THE FILE")
str = [Link]() # Read all data
print(str)
[Link]()
Output:
WRITING DATA IN THE FILE
Enter a sentence: I am a student of class XII
Do you wish to enter more data? (y/n): y
Enter a sentence: my school contact number is 4390xxx8
Do you wish to enter more data? (y/n): n
Byte position of file object: 67
READING DATA FROM THE FILE
I am a student of class XII
my school contact number is 4390xxx8
💡 Key Point
In Program 2-5, after writing data, the file object is at the end of the file. We use seek(0)
to bring it back to the beginning before reading. This is why both read and write can be
performed using a single file object opened in w+ mode.
2.8 The Pickle Module
Python treats everything as an object. Data types like lists, tuples, dictionaries, sets, etc. are also
objects. Sometimes we need to save the state of a Python object (for example, saving the current
state of a game) and retrieve it later.
Python provides the Pickle module for this purpose.
2.8.1 What is Pickling?
Serialization (Pickling): The process of converting a Python object (in RAM) into a byte stream that
can be stored in a binary file, database, or sent across a network.
De-serialization (Unpickling): The reverse process — converting the byte stream back into a Python
object.
📌 Analogy
The name 'Pickle' comes from food preservation — pickling food increases its shelf life.
Similarly, Python's pickle module 'preserves' objects for later use.
Key characteristics of the Pickle module:
• Works with binary files (not text files).
• Data is not 'written' but dumped using dump().
• Data is not 'read' but loaded using load().
• Must be imported before use: import pickle
2.8.2 The dump() Method
Used to pickle (serialize) a Python object and write it to a binary file. The file must be opened in
binary write mode ('wb') or binary append mode ('ab').
Syntax:
[Link](data_object, file_object)
data_object — The Python object to be pickled (list, dict, tuple, etc.).
file_object — The binary file handle to write to.
Program 2-6: Pickling Data in Python
import pickle
# Student record: [roll_no, name, gender, marks]
listvalues = [1, "Geetika", 'F', 26]
fileobject = open("[Link]", "wb") # Open in binary write mode
[Link](listvalues, fileobject) # Serialize and write to file
[Link]() # Always close after pickling
Note: After running this program, [Link] is created containing the serialized (pickled) list.
2.8.3 The load() Method
Used to unpickle (de-serialize) data from a binary file back into a Python object. The file must be
opened in binary read mode ('rb').
Syntax:
store_object = [Link](file_object)
Program 2-7: Unpickling Data in Python
import pickle
print("The data that were stored in file are:")
fileobject = open("[Link]", "rb") # Open in binary read mode
objectvar = [Link](fileobject) # Deserialize (unpickle)
[Link]()
print(objectvar)
Output:
The data that were stored in file are:
[1, 'Geetika', 'F', 26]
2.8.4 File Handling with Pickle — Full Program
Program 2-8 demonstrates complete binary file handling — writing (pickling) employee records and
reading (unpickling) them back.
Program 2-8: Write and Read Employee Records Using Pickle
import pickle
print("WORKING WITH BINARY FILES")
bfile = open("[Link]", "ab") # Append binary mode
recno = 1
print("Enter Records of Employees")
print()
while True:
print("RECORD No.", recno)
eno = int(input("\tEmployee number: "))
ename = input("\tEmployee Name: ")
ebasic = int(input("\tBasic Salary: "))
allow = int(input("\tAllowances: "))
totsal = ebasic + allow
print("\tTOTAL SALARY:", totsal)
edata = [eno, ename, ebasic, allow, totsal]
[Link](edata, bfile) # Pickle employee record
ans = input("Do you wish to enter more records (y/n)? ")
recno += 1
if [Link]() == 'n':
print("Record entry OVER")
print()
break
print("Size of binary file (in bytes):", [Link]())
[Link]()
# Reading back records
print("Now reading employee records from the file")
print()
readrec = 1
try:
with open("[Link]", "rb") as bfile:
while True:
edata = [Link](bfile) # Unpickle one record
print("Record Number:", readrec)
print(edata)
readrec += 1
except EOFError: # Raised when no more records to read
pass
[Link]()
Output:
WORKING WITH BINARY FILES
Enter Records of Employees
RECORD No. 1
Employee number: 11
Employee Name: D N Ravi
Basic Salary: 32600
Allowances: 4400
TOTAL SALARY: 37000
Do you wish to enter more records (y/n)? y
RECORD No. 2
Employee number: 12
Employee Name: Farida Ahmed
Basic Salary: 38250
Allowances: 5300
TOTAL SALARY: 43550
Do you wish to enter more records (y/n)? n
Record entry OVER
Size of binary file (in bytes): 216
Now reading employee records from the file
Record Number: 1
[11, 'D N Ravi', 32600, 4400, 37000]
Record Number: 2
[12, 'Farida Ahmed', 38250, 5300, 43550]
📌 EOFError Handling
When [Link]() tries to read beyond the last record, it raises an EOFError exception.
We use try...except EOFError: pass to gracefully exit the reading loop without crashing
the program.
Common Mistakes to Avoid
1. Forgetting to add \n when using write() — causes all data to appear on one line.
2. Trying to write a number directly — always convert with str() first.
3. Not closing the file — data may not be saved properly.
4. Opening a file in 'w' mode accidentally — erases all existing content.
5. Not using try...except EOFError when reading with [Link]() in a loop.
6. Using seek() with reference_point=1 or 2 in text mode — only works in binary mode.
7. Forgetting import pickle before using the pickle module.