KnowledgeBoat Logo
OPEN IN APP

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 FileBinary File
A text file consists of human readable characters, which can be opened by any text editor.A binary file is made up of non-human readable characters and symbols, which require specific programs to access its contents.
A text file is a file that stores information in the form of a stream of ASCII or Unicode characters.A binary file is a file that stores the information in the form of a stream of bytes.
In text files, each line of text is terminated with a special character known as EOL (End of Line) character.In a binary file, there is no delimiter for a line and no character translations occur here.
Files with extensions like .txt, .py, .csv etc are some examples of text files.Files with extensions like .jpg, .pdf etc are 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 mode and returns the next line in the file or a blank string if there are no more lines.The readlines() function, also reads from a file in read mode and returns 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 a single string to a file.The writelines() method is used to write multiple strings to a file.
The write() method takes a string as an argument.The writelines() method takes an iterable object like lists, tuple, etc. containing strings as an argument.
The write() method returns the number of characters written on to the file.The writelines() method does not return the number of characters written in 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 “example.txt” in both read and write mode.
  2. a binary file “bfile.dat” in write mode.
  3. a text file “try.txt” in append and read mode.
  4. a binary file “btry.dat” in read only mode.

Answer

1. File Mode: 'r+'

fh = open("example.txt", "r+")

2. File Mode: 'wb'

fh = open("bfile.dat", "wb")

3. File Mode: 'a+'

fh = open("try.txt", "a+")

4. File Mode: 'rb'

fh = open("btry.dat", "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

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("practice.txt", "r")
P.read(10)

(b)

with open("practice.txt", "r") as P:
    x = P.read()

Answer

The code given in (a) will open file "practice.txt" 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 "practice.txt" 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 hello.txt. 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("hello.txt", "a")
lines = [
    "Welcome my class\n",
    "It is a fun place\n",
    "You will learn and play"
]
file.writelines(lines)
file.close()

Question 7

Write a Python program to open the file hello.txt 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("hello.txt", "r")
st = " "
while st:
    st = f.readlines()
    print(st)
f.close()

If the file "hello.txt" 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("new.txt", "w")
while True:
    st = input("Enter next line:")
    if st == "END":
        break
    f.write(st + '\n')
f.close()

f = open("new.txt", "r")
while True:
    st = f.readline()
    if not st:
        break
    if st[0].isupper():
        print(st)
f.close()
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("item.dat", '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}
        pickle.dump(item, itemfile)
    print("Successfully written item data")


with open("item.dat", "rb") as file:
    try:
        while True:
            item = pickle.load(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

PrevNext