Chapter 2 - File Handling-Binary File
Chapter 2 - File Handling-Binary File
❑Binary File
❑A Binary file is a file that contains information in the same format in which
the information is held in memory is raw ( with no translation or specific
encoding )
❑We can open some binary files in the normal text editor but we can’t read
the content inside the file.
❑All the binary files will be encoded in the binary format, which can be
understood only by a computer or machine.
❑There is no delimiter to end a line.
❑As the data is already in binary format, translation is not required and
hence processing time will be less.
Difference between Text and Binary files
Text File Binary File
Text Files stores the information in ASCII Binary files are used to store binary data
characters such as images, audio, video and text.
Each line of text is terminated with a There is no delimiter in binary file.
special character known as EOL(End of
line character)
Text files are easy to understand because Binary files are difficult to understand.
they are in human readable form.
Text files are slower than binary files. Binary files are faster and easier to read
and write than text files.
Text files have the extension .txt Binary files have the extension .dat(can
have any application defined extension)s
Less prone to get corrupt as change Can easily get corrupted, corrupt on even
reflects as soon as made and can be single bit change.
undone.
Opening and closing of binary file is same as text file opening and closing. While opening any binary file we
have to specify ‘b’ in file opening mode
Template for any kind of write program(binary)
Template to read from a binary file
e and
e and
e and
Template for read and write combo programs
1 Mark Questions
1. Binary files commonly have the extension :
a) .TXT b) .DAT c) .DOC d) .PDF
5. The mode used for both writing and reading data from a binary file :
a) wb+ b) w c) wb d) a
7. The module pickle is used for which of the methods in file handling :
(a) open( ) and close( )
(b) read( ) and write( )
(c) dump( ) and load( )
(d) None of the above
8. The statement automatically closes the file after processing on the file gets over.
4. Observe the following code and answer the questions that follow :
File = open(“Mydata”,”a”)
_______________# Blank 1
File.close()
a) What type of file( Text / Binary ) is Mydata ?
b) Fill the Blank 1 with statement to write “ABC” in the file Mydata
6. Write in short :
i) What is the use of open( ) method ?
ii) What is the use of tell( ) method ?
8. Answer in brief :
i) Purpose of close( ) function.
ii) Purpose of flush( ) function.
3. a) f1=open(“BOOK.DAT”,”r”)
b) f2=open(“BOOK.DAT”,”w+”)
4. a) Textfile.
b) File.write(“ABC”)
5. i) Option B is correct.
ii) Option A is correct.
3. Write a program that reads a binary file “emp.dat” and displays all records of
employees one by one.
4. Write a program that reads a binary file “emp.dat” and display the records of all
those employees who are getting salary greater than 20000.
5. a) Which method is used to write list, tuple and sequence data types in a binary file ?
b) Which function forces Python to write the contents of buffer to file?
c) Which area is automatically associated with the file when we open it?
3 Marks Questions - Answers
1. a) wb+ mode is used to open a binary file in write and read modes both.
b)ab+ mode is used to open a binary file in append and read mode both.
Previous content is preserved.
c) rb mode is used to open a binary file in read only mode. No other operation can
be performed.
4. import pickle
f1=open("emp.dat","rb")
e=pickle.load(f1)
for x in e :
if(e[x]>20000) :
print(x)
f1.close()
5. a) writelines( )
b) flush( )
c) buffer
4 Marks Questions
3. Create the file phonebook.dat that stores the details in following format :
Name Phone
Alex 7865443
Neha 8855342
Obtain the details from the user
4 Marks questions - answers
1. def Readfile( ) :
i=open(“EMP.DAT”,”rb+”) 2.
x=i.readline() i) Search operation :
while(x) : There is no pre-defined function available in python for searching
I=x.slpit(‘:’) records. It involves reading of the binary file and then comparing each
If ((float(I[2])>=20000) and ( float(I[2])<40000)) : record with our given value. ( This is the linear search process )
print(x) ii) Append operation :
x=i.readline() To add/append data to a binary file, we must open a file in ‘ab’ mode.
i.close() The file will retain the previous records and append the new records at
the end of the file.
iii) Update operation :
In order to update a binary file, the position of the file pointer must be
known. To check the position of the file pointer, we use the functions
tell( ) and seek( )
iv) tell( ) function : It returns the current position of the file pointer in
the file.
Syntax of tell( ) function : variable=file_object.tell( )
3.
fp1==open("phonebook.dat","w")
fp1.write("Name")
fp1.write(" ")
fp1.write("Phone")
fp1.write("\n")
while True :
name=input("Enter name : ")
phno=input("Enter phone no : ")
fp1.write(name)
fp1.write(" ")
fp1.write(phno)
fp1.write("\n")
ch=input("Want to enter more = y / n :")
if ch=='N' or ch=='n’ :
break
fp1.close( )
5 Marks Questions
1. Write a function to write numbers into a binary file and read the same.
2. Read the following passage and answer the questions that follow :
Ramesh, was assigned an incomplete task search( ) function whose purpose was to
search in a pickled file student.dat The following information about student.dat is
known :
● File contains details of students in [ roll, name, marks ] format
● File contains details of 10 students ( ie from roll 1 to 10 ) ans separate list of
each student is written in the binary file using dump( )
Ramesh has been assigned the task to complete the code and print details of roll number 1 .
def search( ) :
f=open("student.dat", ) # statement-1
______________: # statement-2
while True :
rec=pickle.__________ # statement-3
if(__________ ) : # statement-4
print(rec)
except : pass
__________# statement-5
i) In which mode Ramesh should open the file in statement-1 ?
a) r b) r+ c) rb d) wb
ii) Identify the suitable code to be used at blank space in statement-2.
a) if(rec[0]==1) b) for i in range (10) c) try d) pass
iii) Identify the function (with argument) to be used at blank space in
statement-3.
a) load( ) b) load(student.dat) c) load(f) d) load(fin)
iv) What will be the suitable code for blank space in statement-4?
a) rec[0]==2 b) rec[1]==2 c) rec[2]=2 d) rec[0]==1
1. 2.
import pickle def countrec(author):
def createfile(): fobj=open("book.dat","rb")
fobj=open("book.dat","ab") num=0
bookno=int(input("Enter book number:")) try:
bookname=input("Enter book name:") while True:
author=input("Enter author name:") rec=pickle.load(fobj)
price=int(input("price of book:")) if author==rec[2]:
rec=[bookno,bookname,author,price] num=num+1
pickle.dump(rec,fobj) print(rec[0],rec[1],rec[2],rec[3])
fobj.close() except:
createfile() fobj.close()
return num
n=countrec("J K Rowling")
print("total records",n)
A binary file “STUDENT.DAT” has structure [admission_number, Name, Percentage].
Write a function countrec() in Python that would read contents of the file “STUDENT.DAT”
and display the details of those students whose percentage is above 75. Also display
number of students scoring above 75%.
import pickle
def countrec():
fobj=open("student.dat","rb")
num = 0
try:
while True:
rec=pickle.load(fobj)
if rec[2]>75:
num = num + 1
print(rec[0],rec[1],rec[2])
except:
fobj.close()
return num
Write a function in python to search and display details, whose destination is “Cochin”
from binary file “Bus.Dat”. Assuming the binary file is containing the following elements in the list:
1. Bus Number
2. Bus Starting Point
3. Bus Destination
import pickle
def countrec():
fobj=open("bus.dat","rb")
num=0
try:
while True:
rec=pickle.load(fobj)
if rec[2]=="Cochin" or rec[2]=="cochin":
num = num + 1
print(rec[0],rec[1],rec[2])
except:
fobj.close()
return num
n=countrec()
print(n)
6. Write a function addrec() in Python to add more new records at the bottom of a binary
file “STUDENT.dat”, assuming the binary file is containing the following structure :
[Roll Number, Student Name]
import pickle
def addrec():
fobj=open("student.dat","ab")
rollno=int(input("Roll Number: "))
sname=input("Student Name :")
rec=[rollno,sname]
pickle.dump(rec,fobj)
fobj.close()
addrec()
7. Write a function searchprod( pc) in python to display the record of a particular product
from a file product.dat whose code is passed as an argument. Structure of product contains
the following elements [product code , product price]
import pickle
def searchprod(pc):
fobj=open("product.dat","rb")
num=0
try:
while True:
rec=pickle.load(fobj)
if rec[0]==pc:
print(rec)
except:
fobj.close()
n=searchprod(1)