This page contains the NCERT Computer Science class 12 chapter 2 File Handling in Python. You can find the solutions for the chapter 2 of NCERT class 12 Computer Science Exercise. So is the case if you are looking for NCERT class 12 Computer Science related topic File Handling in Python questions and answers for the Exercise
Exercise
Question 1
1. Differentiate between:
a)
text file and binary file
b)
readline() and readlines()
c)
write() and writelines()
Answer 1
Answer (tabular format):
a) Text File vs Binary File
Basis
Text File
Binary File
Meaning
Stores data as readable characters (letters, digits, symbols).
Stores data in binary form (0s and 1s / bytes).
Readability
Human readable (can be read using a text editor).
Not human readable (may appear as garbage in a text editor).
Storage form
Characters are stored using ASCII/UNICODE codes.
Data is stored as raw bytes, same as in memory representation.
End of line
Uses EOL (End of Line) marker like
\n.No special EOL concept; depends on file format.
Examples
.txt, .py, .csv.dat, .jpg, .mp3, .mp4, .exeb) readline() vs readlines()
Basis
readline()readlines()What it reads
Reads only one line at a time.
Reads all lines of the file at once.
Return type
Returns a string.
Returns a list of strings.
Newline
\nThe returned line usually ends with
\n (if present).Each string in the list usually ends with
\n (if present).Memory use
Uses less memory (good for large files).
Uses more memory (not suitable for very large files).
c) write() vs writelines()
Basis
write()writelines()What it writes
Writes one string to the file.
Writes multiple strings (list/tuple of strings).
Parameter
A single string.
An iterable (like list/tuple) of strings.
Newline
\nNewline is not added automatically.
Newline is not added automatically.
Return value
Returns number of characters written.
Does not return number of characters.
Question 2
2. Write the use and syntax for the following methods:
a)
open()
b)
read()
c)
seek()
d)
dump()
Answer 2
a) open()
Use: Opens a file and returns a file object / file handle.
Syntax:
file_object = open(file_name, access_mode)
b) read()
Use: Reads data from a file.
Syntax:
data = file_object.read(n) # reads n bytes
data = file_object.read() # reads complete file
c) seek()
Use: Moves the file object pointer (offset) to a specific byte position.
Syntax:
file_object.seek(offset, reference_point)
# reference_point: 0(beginning), 1(current), 2(end)
d) dump()
Use: Writes (stores) a Python object into a binary file using pickle (pickling/serialization).
Syntax:
pickle.dump(data_object, file_object)
Question 3
3. Write the file mode that will be used for opening the following files. Also, write the Python statements to open the following files:
a)
a text file “example.txt” in both read and write mode
b)
a binary file “bfile.dat” in write mode
c)
a text file “try.txt” in append and read mode
d)
a binary file “btry.dat” in read only mode.
Answer 3
a) a text file “example.txt” in both read and write mode
Mode:
r+f = open("example.txt", "r+")
b) a binary file “bfile.dat” in write mode
Mode:
wbf = open("bfile.dat", "wb")
c) a text file “try.txt” in append and read mode
Mode:
a+f = open("try.txt", "a+")
d) a binary file “btry.dat” in read only mode
Mode:
rbf = open("btry.dat", "rb")
Question 4
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
Reason for why is it advised to close a file after we are done with the read and write operations:
•
Closing a file is a good practice because it frees the resources (memory, etc.) used by the system.
•
Data written using
write() is first stored in a buffer. When we close the file, Python flushes (writes) the buffered data to the disk safely.What will happen if we do not close it?
If we do not close the file, data may not get saved properly (especially if the program stops suddenly) and resources may remain occupied unnecessarily.
Will some error message be flashed?
Usually no error message is flashed immediately, but it can cause problems like incomplete writing or file locking issues.
Question 5
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 5
a)
P = open("practice.txt", "r")
P.read(10)
b)
with open("practice.txt", "r") as P:
x = P.read()
Answer:
•
In (a) we open the file using
open() and read only 10 bytes, but we must close the file using P.close() manually.•
In (b) we use with clause, and the file is closed automatically when control goes outside the
with block (even if an exception occurs). Also it reads the entire file because read() is used without ‘n‘.Question 6
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 6
Commands:
# Open file in append mode
f = open("hello.txt", "a")
# Write the lines
f.write(" Welcome my class\n")
f.write("It is a fun place\n")
f.write("You will learn and play\n")
# Close the file
f.close()
Question 7
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 7
Program (Read and display):
# Program to read and display contents of hello.txt
# Open file in read mode
f = open("hello.txt", "r")
# Read complete file content and display
content = f.read()
print(content)
# Close file
f.close()
Difference (write mode vs append mode):
•
If we open in write mode (
w or w+), the previous contents are overwritten (erased).•
If we open in append mode (
a or a+), new data is added at the end of the file and old content remains safe.Question 8
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 8
Program:
# Program to accept sentences till "END", store in a text file,
# and display only those sentences that begin with an uppercase alphabet.
# Step 1: Open file in write mode (creates a new file or overwrites old)
f = open("sentences.txt", "w")
# Step 2: Take input until user enters END
while True:
line = input("Enter a sentence (type END to stop): ")
if line == "END":
break
# Write each sentence in a new line (EOL using \n)
f.write(line + "\n")
# Step 3: Close after writing (flushes buffer safely)
f.close()
print("\nSentences that begin with an uppercase alphabet:\n")
# Step 4: Open the same file in read mode
f = open("sentences.txt", "r")
# Step 5: Read line by line and check first character
for sentence in f:
sentence = sentence.strip() # remove \n
# Check sentence is not empty and starts with uppercase letter
if sentence != "" and sentence[0].isupper():
print(sentence)
# Step 6: Close file
f.close()
Sample Output:
Enter a sentence (type END to stop): This is to be written
Enter a sentence (type END to stop): to the file
Enter a sentence (type END to stop): and preserved
Enter a sentence (type END to stop): END
Sentences that begin with an uppercase alphabet:
This is to be written
Question 9
9. Define pickling in Python. Explain serialization and deserialization of Python object.
Answer 9
Pickling: Pickling is the process of converting a Python object (like list, tuple, dictionary, etc.) into a byte stream and storing it in a binary file.
Serialization: Serialization means converting data/object in memory (RAM) into a stream of bytes (byte stream). In Python pickle, serialization is also called pickling.
Deserialization: Deserialization means converting the stored byte stream back to the original Python object. In pickle, this is called unpickling.
Question 10
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 10
Program:
# Program to store item records in a binary file using pickle
# and then read and display them in required format.
import pickle
# Step 1: Take number of records from user
n = int(input("How many records do you want to enter? "))
# Step 2: Open binary file in write mode (wb)
# (If you want to add more later without deleting old data, use "ab")
bfile = open("items.dat", "wb")
# Step 3: Input records and dump (pickle) them one by one
for i in range(n):
print("\nEnter details for Record", i + 1)
item_no = int(input("Item No (integer): "))
item_name = input("Item Name (string): ")
qty = int(input("Qty (integer): "))
price = float(input("Price (float): "))
# Store record as a list (Python object)
record = [item_no, item_name, qty, price]
# dump() writes the object into binary file (pickling/serialization)
pickle.dump(record, bfile)
# Step 4: Close file after writing
bfile.close()
print("\n--- Now reading records from binary file ---\n")
# Step 5: Open binary file in read mode (rb)
bfile = open("items.dat", "rb")
# Step 6: Read records using load() until EOFError
try:
while True:
record = pickle.load(bfile) # load() reads one object at a time
item_no, item_name, qty, price = record
amount = qty * price
# Display in required format
print("Item No:", item_no)
print("Item Name:", item_name)
print("Quantity:", qty)
print("Price per item:", price)
print("Amount:", amount)
print("-" * 30)
except EOFError:
# End of file reached
pass
# Step 7: Close file
bfile.close()
Sample Output:
How many records do you want to enter? 7
Enter details for Record 1
Item No (integer): 1001
Item Name (string): Laptop
Qty (integer): 2
Price (float): 55000
Enter details for Record 2
Item No (integer): 1002
Item Name (string): Mobile Phone
Qty (integer): 3
Price (float): 32000
Enter details for Record 3
Item No (integer): 1003
Item Name (string): Printer
Qty (integer): 1
Price (float): 17000
Enter details for Record 4
Item No (integer): 1004
Item Name (string): Scanner
Qty (integer): 1
Price (float): 12000
Enter details for Record 5
Item No (integer): 1005
Item Name (string): Wireless Keyboard
Qty (integer): 4
Price (float): 1500
Enter details for Record 6
Item No (integer): 1006
Item Name (string): Wireless Mouse
Qty (integer): 4
Price (float): 900
Enter details for Record 7
Item No (integer): 1007
Item Name (string): Camera
Qty (integer): 1
Price (float): 45000
--- Now reading records from binary file ---
Item No: 1001
Item Name: Laptop
Quantity: 2
Price per item: 55000.0
Amount: 110000.0
------------------------------
Item No: 1002
Item Name: Mobile Phone
Quantity: 3
Price per item: 32000.0
Amount: 96000.0
------------------------------
Item No: 1003
Item Name: Printer
Quantity: 1
Price per item: 17000.0
Amount: 17000.0
------------------------------
Item No: 1004
Item Name: Scanner
Quantity: 1
Price per item: 12000.0
Amount: 12000.0
------------------------------
Item No: 1005
Item Name: Wireless Keyboard
Quantity: 4
Price per item: 1500.0
Amount: 6000.0
------------------------------
Item No: 1006
Item Name: Wireless Mouse
Quantity: 4
Price per item: 900.0
Amount: 3600.0
------------------------------
Item No: 1007
Item Name: Camera
Quantity: 1
Price per item: 45000.0
Amount: 45000.0