Advertisement

Binary file Handling in Python

 Binary file Handling in Python 

 A binary file stores the data in the same way as as stored in the  memory. The .exe files, mp3 file, image files, word documents are some of the  examples of binary files. We can’t read a binary file using a text editor.

     Ø We can open some binary files in the normal text editor but we can’t read the content present inside the file, because the file will be encoded in the binary format

Ø There is no delimiter to end a line

Ø These files are easy to open and fast working 

Important module in Binary file

1)     1 )Pickling also know as Serialisation or flattening or marshalling.  :

In python, preserving data for future use is called pickling.

Let’s understand in a simple way. If a person who is speaking in German language and a person who is speaking in the Hindi language in communication then it has meaning at all. In this process, we need one person who knows both languages. 

Pickling (Serialisation):  module is doing something exactly (conversion of python objects) in binary. This process is known as pickling.

2)      2) Unpickling or De-serialisation : The inverse of the pickling process is known as unpickling.

The pickle module consists of two main functions :

a)                a)   dump()                 b) load()

a)              dump() function :  these function is used during the pickling process. It convert python object for writing data in a binary file.

Example-1 :

import pickle                                                       # Work with the pickle module

s1 = {'Rno':101,'Name':'Ankita'}                        # s1 and s2 dictionary to be stored in the binary file

s2 = {'Rno':102,'Name':'Jay'}

     f=open("Student.dat","wb")                                  # f is variable file in write mode

pickle.dump(s1,f)                                                 # write onto the file

pickle.dump(s2,f)

f.flush()

print("Data insert successfully...")

________________________________________________________________________________

Example-2 :  # Insert information by users (Input method)

import pickle

stu = {}

f=open("Student.dat","wb")

ans = 'y'

while ans == 'y':

    rno=int(input("Enter roll number "))

    name=input("Enter Name  ")

     stu['Rollno']=rno

    stu['Name']=name

     pickle.dump(stu,f)

    ans = input("Want to enter more records?(Y / N)")

    p.close()

____________________________________________________________________________

a)               load() function  : these function is used during the unpickling process. It is used to load data from a binary file

Example.

 

import pickle

stu = {}                                                          #declare empty dictionary to hold read records

f=open("Student.dat","rb")                            # read from the file

try:                                                                 # try and except check the note

    while True:

        stu = pickle.load(f)

        print(stu)

except EOFError:

        f.close()


·         Note: Use try and except blocks:- Try and Except statement is used to handle these errors within our code in Python. The try block is used to check some code for errors,

EOFError: if End-Of-File is hit without reading any data

________________________________________________________________________________

Example-1.: Searching data

import pickle

stu={}

found = False

f=open("Student.dat","rb")

Searchkeys = [101,102]

try:

    print("Searching in file..")

    while True:

        stu=pickle.load(f)

        if stu['Rno']in Searchkeys:

            print(stu)

            found = True

except EOFError:

    if found == False:

        print("NO such records found")

    else:

        print("Search sucessful..")

    f.close()

 

Example-2.: Searching data by users  (Input method)

import pickle

stu={}

found = False

rollno = int(input("Enter Roll No"))

f=open("Student.dat","rb")

try:

    while True:

        stu=pickle.load(f)

        if stu['Rno'] == rollno:

            print(stu)

            found = True

except EOFError:

    if found == False:

        print("NO such records found")

    else:

        print("Search sucessful..")

    f.close()

___________________________________________________________________________________

First Page of File Handling                                                                     Next: Data Structures 

_______________________________________________________________________