Saturday, July 11, 2020

Python Binary File Program Solution from Sumita Arora Text Book Question 's


1.Write dictionary into a binary file

import pickle
d={'python':90,'java':80,'C++':85}
f=open('abc.dat','wb')   # open binary file in write mode 
pickle.dump(d,f# dump d into f
f.close()

2. Read dictionary from  a binary file
import pickle  

f=open('abc.dat','rb')   # rb read binary file mode as rb
dic=pickle.load(f)  #Read object from a pickle file or binary file
f.close()
print(dic)

3. Writing and reading integers from binary file
import pickle  
f=open('numbers.dat','wb')
n=int(input("how many number you want to enter?"))
for i in range(n):
    x=int(input("enter number\n"))
    pickle.dump(x,f)
f.close()
f=open('numbers.dat','rb')
for i in range(n):
    y=pickle.load(f)  #Read object from a pickle file or binary file
    print(y)
f.close()

4. Writing List in binary file
import pickle
list=[1,2,3,4,5,6,7,8,9,10]
f=open('abc.dat','wb')
pickle.dump(list,f# dump list into f
f.close()


5. Write employee name and salary into binary file

import pickle
f=open('emp.dat','wb')
n=int(input("Enter no of employees\n"))
d={}
i=1
while i<=n:
              name=input("Enter name")
              salary=int(input("Enter salary"))
              d[name]=salary
              i=i+1

pickle.dump(d,f)  # dump d into f
f.close()

6. Reading employ name and salary where salary greater then 4000 from binary file emp.dat
import pickle
f=open("emp.dat","rb")
rd=pickle.load(f)
for key,value in rd.items():
              if(value>4000):

                            print(key,":",value)



No comments:

Post a Comment