Section-III
38. A binary file "EMP.DAT" has structure (E_id, EMP_Name, Age, Salary). Write a
function disprec() in Python that would read contents of the file "EMP.DAT" and display
the details of those EMPLOYEE whose salary > 10000.
5
OR
A binary file "Product dat" has structure [Pno, P_Name, Quantity, Price]
i. Write a user defined function CreateFile() to input data for a record and add to
Product dat.
ii. Write a function DispRec () in Python to display only those product records whose
quantities are more than 100 from the binary file "Product.dat"
Answers
Language:
Python.
Answer:
38. Program goes like:
def disprec():
import pickle
f=open('Emp.dat','rb')
read=pickle.load(f)
for i in read:
if i[3]>10000: #since salary is at index 3.
print (i)
f.close()
Option OR answer:
i) Program 2 goes like:
def CreateFile():
import pickle
f=open('product.dat','wb')
records=[]
while True:
pno=input("Enter product number: ")
pna=input("Enter product name: ")
quan=int(input("Enter quantity: "))
price=float(input("Enter price: "))
choice= input("Wanna enter more (Y/N)?")
records.append([pno,pna,quan,price])
if choice=="N":
break
pickle.dump(records,f)
print(len(records), ' records added.')
f.close()
ii)
def DispRec():
import pickle
f=open('product.dat','rb')
read=pickle.load(f)
for i in read:
if i[2]>100:
print(i)
f.close()
Explanation:
- In program 1 using pickle module we read the binary file data and display it as per our condition.
- In program 2 function 1 def defines a function and uses while loop to except data and dumps it into a binary file using pickle module.
- in program 2 function2 we use pickle.load(f) to read data from binary file f and display the data if the element in every 3rd record which is quantity is when greater than 100