Test Index

File Handling in Python Get it on Google PlayDownload on the App Store CBSE Board Videos

© examsnet.com
Question : 31 of 37
Marks: +1, -0
Shreyas is a programmer, who has recently been given a task to write a user defined function named write_bin( ) to create a binary file called Cust_file.dat containing customer information – customer number (c_no), name (c_name), quantity (qty), price (price) and amount (amt) of each customer.
The function accepts customer number, name, quantity and price. Thereafter, it displays the message ‘Quantity less than 10..... Cannot SAVE’, if quantity entered is less than 10. Otherwise the function calculates amount as price * quantity and then writes the record in the form of a list into the binary file.
import pickle
def write_bin():
bin_file=________ #Statement 1
while True:
c_no=int(input("enter customer number"))
c_name=input("enter customer name")
qty=int(input("enter qty"))
price=int(input("enter price"))
if _______ #Statement 2
print("Quantity less than 10..Cannot SAVE")
else:
amt=price * qty
c_detail=[c_no,c_name,qty,price,amt]
_______ #Statement 3
ans=input("Do you wish to enter more records y/n")
if ans.lower()=='n':
_________ #Statement 4
____________ #Statement 5
______________ #Statement 6
(i) Write the correct statement to open a file 'Cust_file.dat' for writing the data of the customer. [1]
(ii) Which statement should Shreyas fill in Statement 2 to check whether quantity is less than 10. [1]
(iii) Which statement should Shreyas fill in Statement 3 to write data to the binary file and in Statement 4 to stop further processing if the user does not wish to enter more records. [2]
OR
(Option for part (iii) only)
(iii) What should Shreyas fill in Statement 5 to close the binary file named Cust_file.dat and in Statement 6 to call a function to write data in binary file ? [2]
[CBSE 2023 Set 4]
Solution:  
(i) Statement 1:
bin_file = open("Cust_file.dat", "wb")
Mode "wb" opens a binary file for writing ("ab" would add to an existing file).
(ii) Statement 2:
if qty < 10:
(iii)
pickle.dump(c_detail, bin_file)     # Statement 3
break # Statement 4
pickle.dump() writes the list to the binary file; break leaves the while True loop when the user enters n.
OR (iii)
bin_file.close()                    # Statement 5
write_bin() # Statement 6
Statement 5 (after the loop, inside the function) closes the file; Statement 6 (outside the function) calls write_bin() so that the data is written.
© examsnet.com
Advertisements
Go to Question: