Python Tutorial | Python Data File Handling 14

Example:7
To read the roll,name and per stored in  binary file. (created in Example:6)
Sol: (Method:1)

# to read data from a binary file
import pickle
f=open("student","rb")
temp=pickle.load(f)
f.close()
#print(temp)
for i in temp:
    print(i)

# Output 

101 amit 98.89
102 Mohan 87.89
103 Kishan 99.99
104 Abhi 98.78
>>> 

Example:8
To read the roll,name and per stored in  binary file. (created in Example:6)
Sol: (Method:2)

# to read data from a binary file
import pickle
f=open("student","rb")
temp=pickle.load(f)
f.close()
#print(temp)
for rec in temp:
    for field in rec.split():
        print(field,end='\t')
    print('\n')

#Output

101	amit	98.89	

102	Mohan	87.89	

103	Kishan	99.99	

104	Abhi	98.78	

>>> 

Example:9
Python program to take input for employee details like empno,name and salary further write them in a binary file.
Sol:

import pickle

#function definition
def write_emp():
    lst=[]
    while True:
        empno=int(input("Enter empno "))
        name=input("Enter name ")
        sal=float(input("Enter salary "))
        d=str(empno)+' '+name+' '+str(sal)
        lst.append(d)
        ch=input("Like to add more employee records(y/n) ")
        if(ch=='y' or ch=='Y'):
            continue
        else:
            break
    fp=open("emp","wb")
    pickle.dump(lst,fp)
    print("Employee records written in the file")
    fp.close()

#function calling
write_emp()
#Output

Enter empno 1001
Enter name abc
Enter salary 12000
Like to add more employee records(y/n) y
Enter empno 1002
Enter name xyz
Enter salary 23000
Like to add more employee records(y/n) y
Enter empno 1003
Enter name aaa
Enter salary 25000
Like to add more employee records(y/n) n
Employee records written in the file
>>> 

Visitor Counter

0051051