I am trying to write & display the id ,name and salary of 3 employees from .dat file using pickle methods in Python but while displaying I am able to see only 1 employee details the rest are not coming. Please suggest as where the problem is in the below code.
import pickle
class Emp:
def __init__(self, id, name, sal):
self.id = id
self.name = name
self.sal = sal
def display(self):
print('{} {} {}'.format(self.id, self.name, self.sal))
n = int(input('How many employees?'))
for i in range(n):
id = int(input('Enter the id:'))
name = input('Enter name:')
sal = float(input('Enter salary: '))
f = open('emp.dat', 'wb')
e = Emp(id, name, sal)
pickle.dump(e, f)
f = open('emp.dat', 'rb')
print('Employee details: ')
obj = pickle.load(f)
obj.display()
Example run:
INPUT:
How many employees?2
Enter the id:12
Enter name:john
Enter salary: 89000
Enter the id:34
Enter name:mark
Enter salary: 83111
obj.display()
OUTPUT:
Employee details:
12 john 89000.0
wb, as @Tomerikoo rightfully suggested, it "truncates the file upon opening".