Computer Science
Following is the structure of each record in a data file named "PRODUCT.DAT".
{"prod_code": value, "prod_desc": value, "stock": value}
The values for prodcode and proddesc are strings and the value for stock is an integer.
Write a function in Python to update the file with a new value of stock. The stock and the product_code, whose stock is to be updated, are to be inputted during the execution of the function.
Answer
Let the file "PRODUCT.dat" include the following sample data:
{'prod_code': 'AB', 'prod_desc': 'Books', 'stock': 50}
{'prod_code': 'AC', 'prod_desc': 'Pens', 'stock': 75}
{'prod_code': 'AD', 'prod_desc': 'Pencils', 'stock': 30}
import pickle
def update_stock(file_name, product_code, new_stock):
products = []
f = open(file_name, 'rb')
while True:
try:
product = pickle.load(f)
products.append(product)
except EOFError:
break
f.close()
updated = False
for product in products:
if product['prod_code'] == product_code:
product['stock'] = new_stock
updated = True
break
f = open(file_name, 'wb')
for product in products:
pickle.dump(product, f)
f.close()
P_code = input("Enter the product code: ")
New = int(input("Enter the new stock value: "))
update_stock('PRODUCT.DAT', P_code, New)
Output
Enter the product code: AB
Enter the new stock value: 100
The file "PRODUCT.dat" include the following updated data:
{'prod_code': 'AB', 'prod_desc': 'Books', 'stock': 100}
{'prod_code': 'AC', 'prod_desc': 'Pens', 'stock': 75}
{'prod_code': 'AD', 'prod_desc': 'Pencils', 'stock': 30}
Related Questions
Give the output of the following snippet:
import pickle list1, list2 = [2, 3, 4, 5, 6, 7, 8, 9, 10], [] for i in list1: if (i % 2 == 0 and i % 4 == 0): list2.append(i) f = open("bin.dat", "wb") pickle.dump(list2, f) f.close() f = open("bin.dat", "rb") data = pickle.load(f) f.close() for i in data: print(i)
Anant has been asked to display all the students who have scored less than 40 for Remedial Classes. Write a user-defined function to display all those students who have scored less than 40 from the binary file "Student.dat".
Given a binary file "STUDENT.DAT", containing records of the following type:
[S_Admno, S_Name, Percentage]
Where these three values are:
S_Admno — Admission Number of student (string)
S_Name — Name of student (string)
Percentage — Marks percentage of student (float)Write a function in Python that would read contents of the file "STUDENT.DAT" and display the details of those students whose percentage is above 75.
Write statements to open a binary file C:\Myfiles\Text1.txt in read and write mode by specifying file path in two different formats.