Python Tutorial | Python Data File Handling 13

Example:4
To read the names stored in the above binary file.
Sol:
Method:1

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

Output

['Amit', 'Kapil', 'Mohit', 'Kishan']
>>> 

Example:5
To read the names stored in the above binary file.
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 i in temp:
    print(i)

Output:

['Amit', 'Kapil', 'Mohit', 'Kishan']
Amit
Kapil
Mohit
Kishan
>>> 

Example:6
Python program to take input for roll,name and per of students and further write them in a binary file.
Sol:

import pickle

#function definition
def write_details():
    lst=[]
    while True:
        r=int(input("Enter roll "))
        n=input("Enter name ")
        p=float(input("Enter per "))
        d=str(r)+' '+n+' '+str(p)
        lst.append(d)
        ch=input("Like to add more student records (y/n) ")
        if(ch=='y' or ch=='Y'):
            continue
        else:
            break
    fp=open("student","wb")
    pickle.dump(lst,fp)
    print("Names written in the file")
    fp.close()

#function calling
write_details()

Output:

Enter roll 101
Enter name kamal
Enter per 98.90
Like to add more student records (y/n) y
Enter roll 102
Enter name Kishan
Enter per 99.98
Like to add more student records (y/n) y
Enter roll 103
Enter name Mohan
Enter per 98.78
Like to add more student records (y/n) n
Names written in the file
>>> 

Visitor Counter

0056741