Chapter 2
File Handling in Python
Class 12 - NCERT Computer Science
Solutions
Exercise
Question 1(a)
Differentiate between text file and binary file.
Answer
Text File Binary File
A binary file is made up of non-human
A text file consists of human readable
readable characters and symbols, which
characters, which can be opened by
require specific programs to access its
any text editor.
contents.
A text file is a file that stores
A binary file is a file that stores the
information in the form of a stream of
information in the form of a stream of bytes.
ASCII or Unicode characters.
In text files, each line of text is
terminated with a special character In a binary file, there is no delimiter for a line
known as EOL (End of Line) and no character translations occur here.
character.
Files with extensions like .txt, .py, .csv Files with extensions like .jpg, .pdf etc are
etc are some examples of text files. some examples of binary files.
Question 1(b)
Differentiate between readline() and readlines().
Answer
readline() readlines()
The readline() function reads from a file in read The readlines() function, also reads
mode and returns the next line in the file or a from a file in read mode and returns
blank string if there are no more lines. a list of all lines in the file.
The returned data is of string type. The returned data is of list type.
Question 1(c)
Differentiate between write() and writelines().
Answer
write() writelines()
The write() method is used to write The writelines() method is used to write multiple
a single string to a file. strings to a file.
The writelines() method takes an iterable object
The write() method takes a string as
like lists, tuple, etc. containing strings as an
an argument.
argument.
The write() method returns the
The writelines() method does not return the
number of characters written on to
number of characters written in the file.
the file.
Question 2
Write the use and syntax for the following methods:
1. open()
2. read()
3. seek()
4. dump()
Answer
1. open() — The open() method opens the given file in the given mode and associates it
with a file handle. Its syntax is file_object = open(file_name, access_mode).
2. read() — The read() method is used to read data from a file object. It reads at most 'n'
bytes from the file, where 'n' is an optional parameter. If no 'n' is specified, the read()
method reads the entire contents of the file. Its syntax is: file_object.read(n).
3. seek() — This method is used to position the file object at a particular position in a
file. Its syntax is: file_object.seek(offset [, reference_point]).
4. dump() — This method is used to convert (pickling) Python objects for writing data
in a binary file. Its syntax is : dump(data_object, file_object).
Question 3
Write the file mode that will be used for opening the following files. Also, write the Python
statements to open the following files:
1. a text file “[Link]” in both read and write mode.
2. a binary file “[Link]” in write mode.
3. a text file “[Link]” in append and read mode.
4. a binary file “[Link]” in read only mode.
Answer
1. File Mode: 'r+'
fh = open("[Link]", "r+")
2. File Mode: 'wb'
fh = open("[Link]", "wb")
3. File Mode: 'a+'
fh = open("[Link]", "a+")
4. File Mode: 'rb'
fh = open("[Link]", "rb")
Question 4
Why is it advised to close a file after we are done with the read and write operations? What
will happen if we do not close it ? Will some error message be flashed ?
Answer
4 It is a good practice to close a file once we are done with the read and write
operations. When we close a file, the system frees the memory allocated to it. Python ensures
that any unwritten or unsaved data is flushed (written) to the file before it is closed.
Therefore, it is always advised to close the file once our work is done. If we do not close file
explicitly it will close automatically later when it's no longer in use or when the program
terminates, without displaying any error message.
Question 5
What is the difference between the following set of statements (a) and (b):
(a)
P = open("[Link]", "r")
[Link](10)
(b)
with open("[Link]", "r") as P:
x = [Link]
+ad()
Answer
The code given in (a) will open file "[Link]" in read mode and will read 10 bytes from it.
Also, it will not close the file explicitly. On the other hand, the code given in (b) will open
file "[Link]" in read mode and will read the entire content of the file. Furthermore, it will
automatically close the file after executing the code due to the with clause.
Question 6
Write a command(s) to write the following lines to the text file named [Link]. Assume that
the file is opened in append mode.
“ Welcome my class”
“It is a fun place”
“You will learn and play”
Answer
file = open("[Link]", "a")
lines = [
"Welcome my class\n",
"It is a fun place\n",
"You will learn and play"
]
[Link](lines)
[Link]()
Question 7
Write a Python program to open the file [Link] used in question no 6 in read mode to
display its contents. What will be the difference if the file was opened in write mode instead
of append mode?
Answer
f = open("[Link]", "r")
st = " "
while st:
st = [Link]()
print(st)
[Link]()
If the file "[Link]" was opened in write mode instead of append mode, it would have
overwritten the existing content of the file. In write mode ("w"), opening the file truncates its
content if it already exists and starts writing from the beginning. Therefore, the previous
contents of the file would have been replaced with the new lines provided in the write mode
code snippet.
Question 8
Write a program to accept string/sentences from the user till the user enters “END” to. Save
the data in a text file and then display only those sentences which begin with an uppercase
alphabet.
Answer
f = open("[Link]", "w")
while True:
st = input("Enter next line:")
if st == "END":
break
[Link](st + '\n')
[Link]()
f = open("[Link]", "r")
while True:
st = [Link]()
if not st:
break
if st[0].isupper():
print(st)
[Link]()
Output
Enter next line:Hello world
Enter next line:welcome to
Enter next line:Python programming
Enter next line:END
Hello world
Python programming
Question 9
Define pickling in Python. Explain serialization and deserialization of Python object.
Answer
The pickling process serializes objects and converts them into a byte stream so that they can
be stored in binary files.
Serialization is the process of transforming data or an object in memory (RAM) into a stream
of bytes called byte streams. These byte streams, in a binary file, can then be stored on a disk,
in a database, or sent through a network. The serialization process is also called pickling.
Deserialization or unpickling is the inverse of the pickling process, where a byte stream is
converted back into a Python object.
Question 10
Write a program to enter the following records in a binary file :
Item No — integer
Item_Name — string
Qty — integer
Price — float
Number of records to be entered should be accepted from the user. Read the file to display
the records in the following format:
Item No :
Item Name :
Quantity :
Price per item :
Amount : ( to be calculated as Price * Qty)
Answer
import pickle
with open("[Link]", 'wb') as itemfile:
n = int(input("How many records to be entered? "))
for i in range(n):
ino = int(input("Enter item no: "))
iname = input("Enter item name: ")
qty = int(input("Enter quantity: "))
price = float(input("Enter price: "))
item = {"Item no": ino, "Item Name": iname, "Qty":
qty, "Price": price}
[Link](item, itemfile)
print("Successfully written item data")
with open("[Link]", "rb") as file:
try:
while True:
item = [Link](file)
print("\nItem No:", item["Item no"])
print("Item Name:", item["Item Name"])
print("Quantity:", item["Qty"])
print("Price per item:", item["Price"])
print("Amount:", item["Qty"] * item["Price"])
except EOFError:
pass
Output
How many records to be entered? 5
Enter item no: 11
Enter item name: Mobile
Enter quantity: 4
Enter price: 20000
Enter item no: 12
Enter item name: Laptop
Enter quantity: 2
Enter price: 35000
Enter item no: 13
Enter item name: Computer
Enter quantity: 1
Enter price: 50000
Enter item no: 14
Enter item name: Television
Enter quantity: 4
Enter price: 25000
Item No: 11
Item Name: Mobile
Quantity: 4
Price per item: 20000.0
Amount: 80000.0
Item No: 12
Item Name: Laptop
Quantity: 2
Price per item: 35000.0
Amount: 70000.0
Item No: 13
Item Name: Computer
Quantity: 1
Price per item: 50000.0
Amount: 50000.0
Item No: 14
Item Name: Television
Quantity: 4
Price per item: 25000.0
Amount: 100000.0