Skip to main content

Reading and Writing Binary Files

Enter your email address:

मैल पर फीड बर्नर से प्राप्त लिंक Verify करे


Computer Science 
( Class XII Sc ) 
( Subject Code 083)



Reading and Writing binary files





dump() method is used to write the object in binary file and load() method is used to read the object form file



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)

7.Display name of employees where salary greater then 10000 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)

Comments

Popular posts from this blog

Revision basics of Python covered in Class XI

Reading Text Files

Writing CSV Files