Binary File
Binary File
Binary files :- store data in the binary format (0’s and 1’s) which is understandable by
the machine. So when we open the binary file it converts and displays data in a human-
readable format.
To read the data from a binary file, we have to use load( ) function of pickle module.
To read the data from a binary file, we have to use load( ) function of pickle module.
Pickling: Pickling is the process whereby a Python object is converted into a byte
stream.
Unpickling: A byte stream is converted into Python object
import pickle
def get( ):
f=open('stu.dat' , 'wb')
a=int(input('roll'))
b=input('name')
c=int(input('marks'))
z=[a,b,c]
pickle.dump(z,f)
f.close( )
def show( ):
f=open('stu.dat' , 'rb')
try:
while True:
z=pickle.load(f)
print(z)
except:
f.close( )
get ( )
show ( )
A Binary file stu.dat contains[roll , name , marks ] Define the following
writestudent ( ):-To input values of roll number , name , marks and
store it in file stu.dat
display ( ):- To display records of those students where marks are more
then 75
import pickle
def writestudent( ):
f=open('stu.dat' , 'ab')
a=int(input('roll'))
b=input('name')
c=int(input('marks'))
z=[a,b,c]
pickle.dump(z,f)
f.close( )
def display( ):
f=open('stu.dat' , 'rb')
try:
while True:
z=pickle.load(f)
if z[2] > 75 :
print(z)
except:
f.close( )
writestudent( )
display( )
A binary file ' result.dat contains [name , subject , marks] define following
below mentioned functions
display ( ):- To print name and marks of those students whose subject
is computer
import pickle
def accept( ):
f=open('result.dat' , 'ab' )
a=input('name')
b=input('subject')
c=input('marks')
z=[ a,b,c ]
pickle.dump( z , f )
f.close( )
def display( ):
f=open('result.dat' , 'rb')
try:
while True:
z=pickle.load(f)
if z[1]=='computer':
print(z[0] , z[1])
except:
f.close( )
accept( )
display( )
A binary file ' stu.dat ' contains [roll , name , marks] Define functions
add ( ):- To add records into 'stu.dat'
copy( ):- To copy those records into 'pass.dat' where marks is more then
50 and also count number of records copied
import pickle
def add( ):
f=open('stu.dat' , 'ab')
a=int(input('roll'))
b=input('name')
c=int(input('marks'))
z=[a,b,c]
pickle.dump(z,f)
f.close( )
def copy( ):
f=open('stu.dat' , 'rb')
f2=open('pass.dat' , 'ab')
c=0
try:
while True:
z=pickle.load(f)
print(z)
if z[2] > 50 :
pickle.dump(z,f2)
c=c+1
except:
f.close( )
f2.close( )
print(c)
add( )
copy( )
A binary file ' library.dat ' contains [Book-ID , book name, price] define a
function
f=open('library.dat' , 'ab')
a=int(input('Book-ID'))
b=input('Book name')
c=int(input('price'))
z=[a,b,c]
pickle.dump(z,f)
f.close( )
try:
while True:
z=pickle.load(f)
if z[0]==n :
print(z)
except:
f.close( )
add( )
n=int (input('Book-ID'))
search(n )