Binary File Operations
A binary file is just a file that contains information in the same format in which the information is held in the memory. In binary
file, there is no delimiter for a line. Also no translation occurs in binary file. As a result the binary files are faster and easier for a
program to read and write than are the text files. As long as the files doesn’t need to be read by people or need to be ported to
a different type system, binary files are the best way to store the program.
converting structure to a byte stream before writing to the file. While reading the contents of the file a reverse process called
Unpickling is used to convert the byte stream back to the original structure.
We know that the methods provided in python for writing/reading a file work with string parameter. So when we want to work
on a binary file, the conversion of data at the time of reading as well as writing is required.
“Pickle” method can be used to store any kind of object in a file as it allows us to store Python objects with their structures. So
for storing data in binary format we will use “pickle” method.
First, we need to import the module. It provides two main methods for the purpose- dump and load.
import pickle
Opening File Modes:
Mode Details
rb Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is the default
mode.
rb+ Opens a file for both reading and writing in binary format. The file pointer placed at the beginning of the file.
wb Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates a new
file for writing.
wb+ Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not
exist, creates a new file for reading and writing.
ab Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists. That is, the file is in
the append mode. If the file does not exist, it creates a new file for writing.
ab+ Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file exists.
The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing
dump:
For creation of a binary file we will use pickle.dump() to write object in the file, which is opened in binary access mode.
Syntax of dump() method:
dump(object,fileobject)
load:
Once data is stored in the file using dump(), then we can read the stored data using pickle.load() method.
Syntax of load() method:
object=load(fileobject)
1. To create and write data of a list to a binary file
# to create and write data in a binary file
import pickle
#function definition
list1=[10,20,30,40,100]
f=open("data.dat","wb")
pickle.dump(list1,f)
print("Data successfully written into Binary file")
f.close()
2. To read the contents from the above created binary.
# to read data from a binary file
import pickle
f=open("data.dat","rb")
temp=pickle.load(f)
f.close()
print(temp)
3. To take input for names of students and further write them in a binary file.
import pickle
#function definition
def write_names():
lst=[]
while True:
n=input("Enter name ")
lst.append(n)
ch=input("Like to add more names ")
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_names()
4. To read the names stored in the above binary file.
# to read data from a binary file
import pickle
f=open("student","rb")
temp=pickle.load(f)
f.close()
print(temp)
5. To read the names stored in the above binary file.
# 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)
6. Python program to take input for roll, name and per of students and further write them in a binary file.
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()
7. To read the roll, name and per stored in binary file. (created in Example:6)
# 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)
8. To read the roll, name and per stored in binary file. (created in Example:6)
# to read data from a binary file
import pickle
f=open("student","rb")
temp=pickle.load(f)
f.close()
#print(temp)
for rec in temp:
for field in rec.split():
print(field,end='\t')
print('\n')
9. Python program to take input for employee details like empno, name and salary further write them in a binary file.
import pickle
#function definition
def write_emp():
lst=[]
while True:
empno=int(input("Enter empno "))
name=input("Enter name ")
sal=float(input("Enter salary "))
d=str(empno)+' '+name+' '+str(sal)
lst.append(d)
ch=input("Like to add more employee records(y/n) ")
if(ch=='y' or ch=='Y'):
continue
else:
break
fp=open("emp","wb")
pickle.dump(lst,fp)
print("Employee records written in the file")
fp.close()
#function calling
write_emp()
10.Python program to read empno, name and salary stored in the above binary file.( in example:9)
# to read data from a binary file
import pickle
f=open("emp","rb")
temp=pickle.load(f)
f.close()
#print(temp)
for rec in temp:
for field in rec.split():
print(field,end='\t')
print('\n')