Binary file
- We can open binary file in text editor , but we can not read the content.
- In binary file there is no delimiter to end a line.
- No translation takes place that’s why faster than text file.
- For example image file, video , audio, exe etc
Operations performed on binary file
- Write record in a binary file.
- Read record from a binary file
- Append record from a binary file.
- Search record from a binary file.
- Update record from a binary file.
Pickling and Unpickling
Pickling refers to the process of converting the structure(such as list
or dictionary) to a byte before writing to the file.
Two modules of pickles are:-
- Dump
- Load
pickle.dump()
- Used to write any data in a file.
- Syntax:-
- Structure=pickle.load(file object)
Where structure can be any sequence of python. It can be either list or dictionary.
• File object is the file handle helps to connect with a file in reading the content.
pickle.load()
- Used to read the data from a file.
- Syntax:-
- Structure=pickle.load(file object) Where structure can be any sequence of python. It can be either list or dictionary.
- File object is the file handle helps to connect with a file in
reading the content.
Program to write list and dictionary in a file using pickle module
import pickle
def write():
f=open(“binary.dat”,”wb”)
list=[“maths”,”english”,”physics”,”compsci”]
pickle.dump(list,f)
dic={“comp”:100,”maths”:99,”physics”:98}
pickle.dump(dic,f)
f.close()
def read():
f=open(“binary.dat”,”rb”)
list=pickle.load(f)
print(list)
dict=pickle.load(f)
print(dict)
write()
print(“Data written in a file successfully….”)
read()
How to insert multiple records in a file and read it in binary file.
To understand this concept first understand the concept of nested
List. For example
>>> list=[]
>>> list1=[1,”ria”,89]
>>> list.append(list1)
>>> list
[[1, ‘ria’, 89]]
To add another record
>>> list1=[2,”amit”,88]
>>> list.append(list1)
>>> list
[[1, ‘ria’, 89], [2, ‘amit’, 88]]
To access particular value from a record/list
>>> list
[[1, ‘ria’, 89], [2, ‘amit’, 88]]
>>> list[0] # will show first record
[1, ‘ria’, 89]
>>> list[0][0] #will show 0 row 0 column i.e 1
1
>>> list[1] # will show second record
[2, ‘amit’, 88]
>>> list[0][1] # will show 0 row 1 column i.e “ria
‘ria’
>>> list[1][2] # will show 1 row 2nd column i.e 88
88
Program to write multiple records in a binary file
import pickle
def write():
f=open(“bf.dat”,”wb”)
list=[]
while True:
rno=int(input(“Enter roll number:- “))
name=input(“enter name:- “)
marks=int(input(“enter marks:-“))
list1=[1,”ria”,90]
list.append(list1)
ch=input(“Do u want to enter more records”)
if ch==”n”:
break
pickle.dump(list,f)
write()
print(“Records written in file successfully…”)
output
Enter roll number:-1
enter name:- anu
enter marks:-89
Do u want to enter more recordsy
Enter roll number:-2
enter name:- gaurav
enter marks:-87
Do u want to enter more recordsn
Records written in file successfully…
>>>
To read all records all together
def read():
f=open(“bf.dat”,”rb”)
record=pickle.load(f)
print(record)
read()
output
[[1, ‘anu’, 89], [2, ‘gaurav’, 87]]
To read record one by one
def read():
f=open(“bf.dat”,”rb”)
record=pickle.load(f)
for i in record:
print(i)
read()
output
[1, ‘anu’, 89]
[2, ‘gaurav’, 87]
To display the record index wise
import pickle
def write():
f=open(“bf.dat”,”wb”)
list=[]
while True:
rno=int(input(“Enter roll number:-“))
name=input(“enter name:- “)
marks=int(input(“enter marks:-“))
list1=[rno,name,marks]
list.append(list1)
ch=input(“Do u want to enter more records”)
if ch==”n”:
break
pickle.dump(list,f)
def read():
f=open(“bf.dat”,”rb”)
record=pickle.load(f)
for i in record:
rno=i[0]
name=i[1]
marks=i[2]
print(“rollno=”,rno,”Name=”,name,”Marks=”,marks)
#write()
#print(“Records written in file successfully…”)
read()
output
rollno= 1 Name= anu Marks= 89
rollno= 2 Name= gaurav Marks= 87
>>>
How to append record in a binary file
import pickle
def append():
f=open(“bf.dat”,”ab”)
list=[]
while True:
rno=int(input(“Enter roll number:-“))
name=input(“enter name:- “)
marks=int(input(“enter marks:-“))
list1=[rno,name,marks]
list.append(list1)
ch=input(“Do u want to enter more records”)
if ch==”n”:
break
pickle.dump(list,f)
append()
How to read records from a binary file (Another method)
def read():
f=open(“bf.dat”,”rb”)
while True:
try:
record=pickle.load(f)
for i in record:
print(i)
except EOFError:
break
f.close()
output
[1, ‘anu’, 89]
[2, ‘gaurav’, 87]
[3, ‘TIA’, 67]
[4, ‘sumit’, 90]
[3, ‘sia’, 34]
[6, ‘reena’, 45]
How to search record from a binary file
def read():
f=open(“radhey”,”rb”)
while True:
try:
record=pickle.load(f)
for i in record:
print(i)
except EOFError:
break
f.close()
def search():
f=open(“radhey”,”rb”)
record=pickle.load(f)
found=0
roll=int(input(“enter rno which you want to search”))
for i in record:
if roll==i[0]:
found=1
print(“record is”,i)
if found==0:
print(“record does not exist”)
f.close()
read()
search()
output
[4, ‘ram’]
[5, ‘ram’]
[6, ‘shayam’]
[7, ‘hari’]
[9, ‘sia’]
[10, ‘pia’]
enter rno which you want to search4
record is [4, ‘ram’]
Random Access in Files
seek()
tell()
seek() function is used to change the position of the file pointer to a
specific position.
File pointer is like a cursor which defines from where the data has to
be read or write in the file.
Syntax:-
f.seek(offset,from_what)
where f is the file pointer from_what argument can have any of the three values:-
0. sets the reference point at the beginning of the file which is the default.
1. set the reference point at the current file position.
2. set the reference point at the end of the file.
NOTE:-
But in python 3.x and above , we can seek from beginning
only, if opened in text mode. We can overcome from this by opening
the file in b mode.
tell() function will return the location in term of byte
Team NB Learner