Python program to Create a binary file with name and roll number|Search for a given roll number and display the name, if not found display appropriate message OR write a Python program to create a binary file with roll number, name and marks|Input a roll number and update the marks

Introduction

Binary files:-
"Binary" files are any files where the format isn't made up of readable characters. In Python, files are opened in text mode by default. To open files in binary mode, when we are specifying a mode we have to add 'b' to it.
Python has tools to work with binary files. Binary files use strings of type bytes.
The module  needed for performing such operations on binary files is PICKLE.

  • In this blog we are going to create a binary file with name and roll number, search for a given roll number and display the name, if not found display appropriate message.
  • We are going to generate a binary file, open binary file & Modify a binary file.

We are going to perform two programs:
In first program we will enter data in the program by specifying it inside variables.
In Second program the data will be entered by user and the certain operations will be performed.

First program

Source code-


import pickle

with open('students','wb') as b:

    d1={'name':'first','roll number':1}

    pickle.dump(d1,b)

    d2={'name':'second','roll number':2}

    pickle.dump(d2,b)

    d3={'name':'third','roll number':3}

    pickle.dump(d3,b)

roll=int(input('enter the desired roll no:'))

with open('students','rb')as b:

    p=[]

    while True:

        try:

            for i in range(1,4):

                k=pickle.load(b)

                p+=[k['roll number']]

                if roll==k['roll number']:

                    print('the name of the desired student is:',k['name'])

            if roll not in p:

                print('the student of the desired roll no. does not exist')

        except EOFError:

            break
#-------------code ended-----------


Output:-(Click for clear image)

Executed in Pydroid3
  • Library used - pickle
Functions and operators used in the program are:
  • pickle.dump()
  • int(input())
  • while loop
  • pickle.load()
  • for loop
  • print()
  • break
  • in,not in

Second program

Source code-

import pickle
with open('stud-data','wb') as f: 
    record=[]
    while True:
        roll_no=int(input("enter roll number:"))
        name=input("enter the name:")
        marks=int(input("enter the marks:"))
        data=[roll_no,name,marks]
        record.append(data)
        choice=input("do you want to input more data?(y/n)")
        if choice=='n':
            break
    pickle.dump(record,f)
    print ("the data has been entered successfully")
with open ("stud-data",'rb') as f:
    while True:
        try:
            record=pickle.load(f)
            print (f"{'roll no'}\t{'name'}\t{'marks'}")
            for i in record:
                print (f"{i[0]}\t{i[1]}\t{i[2]}")
        except EOFError:
            break
with open('stud-data','rb+') as f:
    found=0
    while True:
        try:
            record=pickle.load(f)
            roll_no=int(input("enter roll no"))
            for i in record:
                if roll_no==i[0]:
                    i[2]=input("enter the new marks")
                    found=1
                    break
            if found==0:
                print ("the record is not found")
            else:
                f.seek(0)
                pickle.dump(record,f)
        except EOFError:
            break
with open ("stud-data",'rb') as f:  
    while True:
        try:
            record=pickle.load(f)
            print (f"{'roll no'}\t{'name'}\t{'marks'}")
            for i in record:
                print (f"{i[0]}\t{i[1]}\t{i[2]}")
        except EOFError:
            break
#-------------code ended-----------

Output:-

Executed in Pydroid3

  • Library used - pickle
Functions and operators used in the program are:
  • pickle.dump()
  • int(input())
  • while loop
  • pickle.load()
  • for loop
  • print()
  • break
  • in,not in

Understanding use of operators and functions:-

  • pickle.dump():-It is used to store the object data to the file.
  • pickle.load()-To retrieve pickled data, the steps are quite simple

What is pickling?

Pickle is used for serializing and de-serializing Python object structures.


So In this Blog we also learnt to create Binary files in Python.

"Hope it helped"
Have anything in mind? Let me 
know in the comment section👇

Next Post Previous Post
No Comment
Add Comment
comment url