Chapter -2 : File Handling in Python
Q.1. What is a file, and why is it used in Python programming?
Answer: A file is a named location on secondary storage where data are permanently stored.
Need for Files in Python:
Variables in Python store data only temporarily during program execution.
Files allow storing input, output, or processed data permanently.
This avoids repetitive tasks like entering the same data repeatedly.
Files are commonly used by organizations to store essential data like employee
details, sales records, and inventory.
Example:
Python programs are saved as files with a .py extension on storage devices.
Data (input and output) can also be saved into files for later use.
Files help achieve data reusability and storage efficiency.
Q.2. What are the types of files? Explain briefly. OR Write the difference between text
file and binary file.
Answer: There are two main types of files in Python: 1. Text files, 2. Binary files
Text Files Binary Files
It is human readable It is not human readable
It uses ASCII or UNICODE It stores data as Bytes (0s & 1s).
characters to store data.
Each line of a text file is terminated No EOL character
by an End of Line (EOL) character
Text files can be easily edited It requires specific software to edit
or modify
Ex.: .txt, .csv etc Ex.: .exe, .mp3 etc
Q.3. How do you open and close a file in Python? Explain with syntax.
Answer :
1. Opening a File: Python provides the open( ) function to open a file.
Syntax: file_object = open(file_name, access_mode)
Example: myObject = open("[Link]", "a+")
Opens [Link] in append and read mode. The file pointer is positioned at the end of
the file.
2. Closing a File:
close() method is used to close a file and release the memory.
Syntax: file_object.close()
Python ensures that any unsaved data is written to the file before closing it.
3. Using with Clause:
A simpler way to open and close a file automatically.
Syntax: with open(file_name, access_mode) as file_object:
Once the block inside with is completed, the file closes automatically.
Example: with open("[Link]", "r+") as myObject:
content = [Link]()
No need to call close() explicitly!
Q.3a: What are the attributes of the file object ?
Aurobindo Composite PU College 1
Chapter -2 : File Handling in Python
Answer :Attributes of File Object:
[Link]: Returns True if the file is closed.
[Link]: Returns the mode in which the file was opened.
[Link]: Returns the name of the file.
Q.3b: What are the file open modes ? OR Explain the various file access modes with
their purpose and example.
Q.4: How can we write data to a text file in Python, and what are the differences
between the write() and writelines() methods?
Answer : In Python, data can be written to a text file using the write() or writelines() methods
after opening the file in write ('w') or append ('a') mode.
write( ) writelines( )
Used for writing a single string to Used for writing multiple strings.
the text file.
Returns the number of characters Does not return the number of
written. characters written.
It takes a string as an argument It takes an iterable object like lists ,
tuple etc … as argument
Q.5: How can we read data from a text file in Python, and what are the different
methods used for reading data?
Answer: In Python, we can read data from a text file after opening it in “r”, “r+”, “w+”, or
“a+” mode. There are three main methods for reading data from a file:
1. read() Method: This method reads the specified number of bytes from a file. If no
argument or a negative number is passed, it reads the entire file.
Syntax: file_object.read(n)
2. readline() Method: This method reads one complete line from the file, up to the newline
3. readlines() Method: This method reads all lines and returns them as a list of strings,
where each line ends with a newline character (\n).
Q.6. Program - Writing and Reading to a Text File.
Answer: This program writes a user-input string to a file and then reads and displays the
content of the file:
Aurobindo Composite PU College 2
Chapter -2 : File Handling in Python
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
Q.7: How can we access data in a random fashion in Python, and what are the functions
used for setting offsets in a file?
In Python, to access data in a random (non-sequential) fashion, we can use the following
functions:
1. tell() Method:
This method returns an integer representing the current byte position of the file object,
measured from the beginning of the file. Syntax: file_object.tell()
2. seek() Method:
This method moves the file object to a specified position.
Syntax: file_object.seek(offset, [, reference_point])
offset: Number of bytes by which the file object is to be moved.
reference_point: Starting position to count the offset from. It can take the following
values:
0 – Beginning of the file (default).
1 – Current position of the file.
2 – End of the file.
Q10: What is the Pickle module in Python, and how does it perform serialization and
deserialization?
Answer : The Pickle module in Python is used for serializing and deserializing Python
objects.
Serialization (pickling) transforms Python objects into a byte stream to store in a
binary file or database or send over a network.
Deserialization (unpickling) is the reverse process that converts the byte stream back
into Python objects.
Methods in Pickle module:
1. dump() method: Used for serializing (pickling) and writing Python objects into a binary
file.
Syntax: [Link](data_object, file_object)
Example:
import pickle
listvalues = [1, "Geetika", 'F', 26]
fileobject = open("[Link]", "wb")
[Link](listvalues, fileobject)
[Link]()
2. load() method: Used for deserializing (unpickling) and reading Python objects from a
binary file.
Syntax: store_object = [Link](file_object)
Example:
import pickle
print("The data that were stored in file are: ")
fileobject = open("[Link]", "rb")
objectvar = [Link](fileobject)
Aurobindo Composite PU College 3
Chapter -2 : File Handling in Python
[Link]()
print(objectvar)
Output of Program:
The data that were stored in file are:
[1, 'Geetika', 'F', 26]
Q.11: How can employee records be stored and retrieved using the Pickle module in
Python?
Answer : Employee records can be written to and read from a binary file using the Pickle
module with minimal steps:
1) Writing Employee Records (Pickling):
import pickle
with open("[Link]", "ab") as bfile:
while True:
eno = int(input("Employee number: "))
ename = input("Employee Name: ")
salary = int(input("Salary: "))
[Link]([eno, ename, salary], bfile)
if input("Add more records (y/n)? ").lower() == 'n':
break
2) Reading Employee Records (Unpickling):
import pickle
with open("[Link]", "rb") as bfile:
try:
while True:
print([Link](bfile))
except EOFError:
pass
Explanation:
The dump() method stores the employee details as a list in the binary file [Link].
The load() method retrieves and displays each record.
The EOFError exception handles the end of the file gracefully.
Output:
Employee number: 11
Employee Name: Ravi
Salary: 32000
Add more records (y/n)? y
Employee number: 12
Employee Name: Farida
Salary: 45000
Add more records (y/n)? n
[11, 'Ravi', 32000]
[12, 'Farida', 45000]
Q.12. Write the syntax of the following methods : a. open( ) b. seek( ) c. lode()
d. dump() e. tell( )
Answer: a. open( ) : file_object= open(file_name, access_mode)
Aurobindo Composite PU College 4
Chapter -2 : File Handling in Python
b. seek( ) : file_object.seek(offset [, reference_point])
c. load( ) : Store_object = load(file_object)
d. dump( ): dump(data_object, file_object)
e. tell( ) : file_object.tell()
Q.13. Briefly explain binary files.
Answer:
Binary file is not human readable.
It stores data as Bytes (0s & 1s).
No EOL character.
It requires specific software to edit or modify.
Ex.: .exe, .mp3 etc
Aurobindo Composite PU College 5