KnowledgeBoat Logo

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.

Python Data Handling

2 Likes

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}

Answered By

1 Like


Related Questions