Lesson-5-File Handling-Binary Files
Lesson-5-File Handling-Binary Files
1
Python provides a special module called pickle module. Python pickle
module is used for serializing and de-serializing a Python object structure.
Pickling is a way to convert a python object (list, dict, etc.) into a character
stream.
Unpickling is the inverse operation, whereby a byte stream (from a binary file
or bytes-like object) is converted back into an object hierarchy(back to the
original structure).
First we need to import the module. It provides two main methods for the
purpose – dump() and load()
For creation of a binary file pickle.dump() is used. This will write objects to the
file which is opened in binary access mode.
dump(object,fileobject)
Examples
def fileoperation():
import pickle
lst=[10,20,30,40]
f=open("list1.dat",'wb')
pickle.dump(lst,f)
print("List added to binary file")
f.close()
fileoperation()
Output
2
import pickle
d1={'Python':90,'Java':95,'C++':85}
f=open('d.dat','wb')
pickle.dump(d1,f)
f.close()
Once data is stored using dump(), it can be used for reading. For reading
data from the binary file, we have to use pickle.load() to read the object
from the pickle file.
Syntax of load()
object=load(fileobject)
Examples
1. Write a program to display the contents of the binary file list1.dat and
display the contents on the screen.
import pickle
f=open("list1.dat","rb")
l=pickle.load(f)
print(l)
Output
2. Write a program to display the contents of the binary file d.dat and
display the contents on the screen.
import pickle
f=open('d.dat','rb')
d=pickle.load(f)
print(d)
Output
3
3. Write a program to insert/append a record in the binary file "student.dat".
import pickle
record=[]
while True:
rollno=int(input("Enter roll number:"))
name=input("Enter name:")
marks=int(input("Enter marks:"))
data=[rollno,name,marks]
record.append(data)
ch=input("Want to enter more records?")
if ch.upper()=='N':
break
f=open("Student.dat","wb")
pickle.dump(record,f)
print("record added")
f.close()
As shown in the above program, inserting and adding record in student file
begins with importing pickle module. Then, iterating for the number of records
to be added is done using while loop. Input is accepted from the user for roll
number, name and marks. These fetched values are saved as a list to be
appended. Once the record is created, it is appended to the binary file “student”
using the dump() method, which writes the object into the opened file. Finally
4
the file is closed explicitly and the record is added into the student.dat file as
shown in the output. Since binary file contains unreadable characters, it
becomes difficult to read and understand, but directly used and understood by
the computer.
import pickle
f=open("Student.dat","rb")
stud_rec=pickle.load(f) # to read the object from the binary file
print("Contents of the file are:")
#reading the fields
for i in stud_rec:
rollno=i[0]
name=i[1]
marks=i[2]
print(rollno,name,marks)
f.close()
Output
Searching the binary file "student" is carried out on the basis of the roll number
entered by the user. The file is opened in the read-binary mode and gets stored
in the file object, f. load() method is used to read the object from the opened
file. A variable ‘found’ is used which will tell the status of the search operation
being successful or unsuccessful. Each record from the file is read and the
contents of the field, roll no, is compared with the roll number to be searched.
Upon the search being successful, appropriate message is printed.
import pickle
f=open("Student.dat","rb")
5
stud_rec=pickle.load(f) # to read the object from the binary file
found=0
rno=int(input("Enter the roll number to search for:"))
for i in stud_rec:
if i[0]==rno:
print("Search Successful",i[1],"found")
found=1
break
if found==0:
print("Record not found")
f.close()
Output
Note
Updating a record in the file requires roll number to be fetched from the user
whose name is to be updated.
6. Write a program to update a record in the file. Enter the roll number of
the student whose name has to be updated.
import pickle
f=open("Student.dat","rb+")
stud_rec=pickle.load(f) # to read the object from the binary file
found=0
rno=int(input("Enter the roll number to search for:"))
for i in stud_rec:
if i[0]==rno:
6
print("Current name is:",i[1])
i[1]=input("Enter the new name:")
found=1
break
if found==0:
print("Record not found")
else:
f.seek(0) # taking the file pointer to the beginning of the file
# program will not work without this statement
pickle.dump(stud_rec,f)
print("Name updated!")
f.close()
Output
Once the record is found, the file pointer is moved to the beginning of the file
using seek(0) statement, and then the changed name is written to the file and the
record is updated. seek() method is used for random access to the file.
#p6.py
#Accepting data for a dictionary
7
def insertrec():
rollno=int(input("Enter the roll number:"))
name=input("Enter the name:")
marks=int(input("Enter marks:"))
#Creating the dictionary
rec={"Rollno":rollno,"Name":name,"Marks":marks}
#Writing to the dictionary
f=open("Stud.dat","ab")
pickle.dump(rec,f)
f.close()
8
f.close()
#Mark modification for a roll number
def updatemarks(r,m):
f=open("stud.dat","rb")
reclist=[]
while True:
try:
rec=pickle.load(f)
reclist.append(rec)
except EOFError:
break
f.close()
for i in range(len(reclist)):
if reclist[i]['Rollno']==r:
reclist[i]['Marks']=m
f=open("stud.dat",'wb')
for x in reclist:
pickle.dump(x,f)
f.close()
def deleterec():
f=open("stud.dat","rb")
reclist=[]
while True:
try:
rec=pickle.load(f)
reclist.append(rec)
except EOFError:
break
f.close()
f=open("stud.dat","wb")
for x in reclist:
if x['Rollno']==r:
continue
pickle.dump(x,f)
f.close()
#__main__
import pickle
while True:
print("1.Insert Record")
print("2.Display Record")
9
print("3.Search Record")
print("4.Update Record")
print("5.Delete Record")
print("0.Exit")
print("Enter your choice:")
ch=int(input("Enter choice:"))
if ch==0:
break
elif ch==1:
insertrec()
elif ch==2:
readrec()
elif ch==3:
r=int(input("Enter a roll number to search:"))
searchrollno(r)
elif ch==4:
r=int(input("Enter a roll number to update:"))
m=int(input("Enter the new marks:"))
updatemarks(r,m)
elif ch==5:
r=int(input("Enter a roll number to delete:"))
deleterec()
Till now in all the programs, sequential processing of data in a text and binary
file was emphasized. But files in Python allow random access of the data as
well using built-in methods seek() and tell().
seek() - seek() function is used to change the position of the file handle (file
pointer) to a given specific position. File pointer is like a cursor, which defines
from where the data has to be read or written in the file. Python file method
seek() sets the file’s current position at the offset.
10
0: sets the reference point at the beginning of the file, which is by default.
1: sets the reference point at the current file position.
2: sets the reference point at the end of the file.
• Absolute Positioning
• Relative Positioning
Absolute referencing using seek() gives the file number on which the file
pointer has to position itself.
For example, f.seek(20) will give the position or file number where the
file pointer has been placed. This statement shall move the file pointer to
20th byte in the file no matter where the pointer is.
Example
Note
Python 3.x only supports text file seeks from the beginning of the file.
seek() with negative offset only works when the file is opened in binary
mode.
11
tell() - tell() returns the current position of the file read/write pointer within the
file.
Syntax
When you open a file in reading/writing mode, the file pointer rests at 0th
byte.
When you open a file in append mode, the file pointer rests at last byte.
Example-1
f=open("test.txt")
print("Before reading",f.tell())
a=f.read()
print("After reading",f.tell())
f.seek(0)
#brings the file to the 0th byte of the file
print("From beginning again",f.tell())
s=f.read(4)
print("First 4 bytes are:",s)
print(f.tell())
s=f.read(3)
print("Next 3 bytes are:",s)
print(f.tell())
f.close()
Output
12
Before reading 0
After reading 35
From beginning again 0
First 4 bytes are: This
4
Next 3 bytes are: is
7
Example-2
f=open("File.txt",'w')
f.write("This is a test\n")
f.write("program in\n")
f.write("Python")
f.close()
f=open("File.txt",'r')
f.seek(10) # by default 0
print(f.tell())
print(f.readline())
f.close()
OR
f=open("File.txt",'r')
f.seek(10,0)
print(f.tell())
print(f.readline())
f.close()
Output
10
test
Note
All the remaining characters from the 10th byte will be displayed until end
of line character.
13
Example-3
f=open("File.txt",'w')
f.write("This is a test") # ‘\n’ removed
f.write("program in\n")
f.write("Python")
f.close()
f=open("File.txt",'r')
f.seek(10)
print(f.tell())
print(f.readline())
f.close()
Output
10
testprogram in
Note
If there is no ‘\n’ in the first line then all the remaining characters from
the 10th byte will be displayed until ‘\n’ will be displayed.
Example-4
f=open("File.txt",'w+')
f.write("This is a test \n")
f.write("program in\n")
f.write("Python")
print(f.readline())
f.close()
14
Output
20
gram in
Example-5
f=open("File.txt",'w')
f.write("This is a test\n") # ’\n’ included
f.write("program in\n")
f.write("Python")
f.close()
f=open("File.txt",'r')
f.seek(10)
print(f.tell())
f.seek(5,0)
print(f.tell())
print(f.readline())
f.close()
Output
10
5
is a test
Note
Example-6
f=open("File.txt",'r')
f.seek(0,1)
print(f.tell())
print(f.readline())
f.close()
15
Output
0
This is a test
Note
Example-7
f=open("File.txt",'rb')
f.seek(0,1)
print(f.tell())
print(f.readline())
f.close()
Output
b'This is a test\r\n'
Example-8
f=open("File.txt",'r')
f.seek(0,2)
print(f.tell())
print(f.readline())
f.close()
Output
34
Example-9
f=open("File.txt",'r')
f.seek(20)
f.seek(10)
print(f.tell())
f.seek(0,1)
16
print(f.tell())
f.seek(5)
print(f.tell())
print(f.readline())
f.close()
Output
10
10
5
is a test
Example-10
f=open("File.txt",'rb')
f.seek(10)
print(f.tell())
print(f.readline())
f.seek(5,1)
print(f.tell())
print(f.readline())
f.seek(5,1)
print(f.tell())
print(f.readline())
f.close()
Output
10
b'test\r\n'
21
b'am in\r\n'
33
b'n'
Example-11
f=open("File.txt",'w')
f.write("This is a test\n")
17
f.write("program in\n")
f.write("Python")
f.close()
f=open("File.txt",'rb')
# sets Reference point to 30th
# position to the left from end
f.seek(-30, 2)
f.close()
Output
4
b' is a test\r\n'
Example-12
f=open("File.txt",'w')
f.write("This is a test\n")
f.write("program in\n")
f.write("Python")
f.close()
f=open("File.txt",'rb')
# sets Reference point to tenth
# position to the left from end
f.seek(-10, 2)
f.close()
Output
24
b'in\r\n'
Note: Reference point at current position / end of file cannot be set in text mode
except when offset is equal to 0.
19