In this article, you will learn about File handling – Binary file operations in Python such as Append, Search, update and delete.

In the previous article, you learned about Basic operations on a binary file such as opening/closing a binary file, the fundamentals of the pickle module and reading and writing in binary files.

So let’s start now, the contents are as follows:

Append data in Binary File

To append data in binary follow these steps:
  1. Open the file in append mode using “ab”  Ex.: f = open (“file.dat”,”ab”)
  2. Enter data to append
  3. Append entered data into the dictionary/list object
  4. Use pickle.dump() method to write the dictionary/list data
  5. Close the file
Observe the following code:
def bf_append():
    f = open("sports.dat","ab")
    print("Append Data")
    pcode = int(input("Enter the Player code:"))
    pname = input("Enter Player Name:")
    score = int(input("Enter individual score:"))
    rank = int(input("Enter Player Rank:"))

Do not run your code without reading the contents.

Reading Data

Follow these steps to read data:
  1. Open the file in read mode using “rb” Ex.: f = open(“File.dat”, “rb”)
  2. Use while loop with True statement to read the entire contents of the file individually.
  3. Use try – except for Exception handling to avoid runtime EOFError
  4. Now load data into an object through the load function
  5. Print data as per need
  6. Close the file

Observe the following code:

  def bf_read():
    f = open("Sports.dat","rb")
    print("Data stored in File....")
    while True:
try: rec= pickle.load(f) print("Player Code:",rec['Pcode']) print("Player Name:",rec['Pname']) print("Individual Score:",rec['Score']) print("Player Rank:",rec['Rank']) print("."*78) except Exception:
break f.close() bf_read() 

Watch this video to append and display a record using list object into binary file.

Search Records from binary file

Follow these steps to search the record in the binary file:
    1. Open the file in reading mode using “rb”
    2. Prompt a message to ask unique field from data to search
    3. Declare a boolean variable flag to store False for the record not found and True when the record found
    4. Use a while loop to access records individually
    5. Now load the data into the dictionary object using load() function
    6. Use if condition to compare the data with the variable taken in step 2
    7. Print the record found
    8. Assign True to the flag variable declared in step 3
    9. Use the except block to handle EOFError and terminate the loop using the break
    10. Print record not found message when Flag is False
    11. Finally, close the file using f.close()

Observe the following code:

def bf_search():
    f = open("Sports.dat","rb")
    pc = int(input("Player to code to search:"))
    while True:
try: rec= pickle.load(f) if rec['Pcode']==pc: print("Player Name:",rec['Pname']) print("Individual Score:",rec['Score']) print("Rank:",rec['Rank']) flag = True except Exception: f.close() if flag==False: print("Record not found...") f.close() bf_search()

Update record in Binary file

To update record you can use the search record code if you wish. To update the record follow these steps:
    1. Open the file using read mode
    2. Declare a variable for unique value to be updated
    3. Use try-except and while loop as explained above
    4. Add record fetched from binary file into a list
    5. Enter the new record information to update
    6. Compare the fetched records with entered record and assign the new values to update
    7. Write the data using dump() function
    8. Close the file

Have look at the following code:

def bf_update():
f = open('student.dat','rb')
reclst = []
while True:
rec = pickle.load(f)
except EOFError:
pc=int(input("Enter player code to update:"))
pn=input("Enter new name:")
ps=int(input("Enter Player Score:"))
pr=int(input("Enter Player Rank:"))
for i in range (len(reclst)):
if reclst[i]['Pcode']==pc:
reclst[i]['Pname'] = pn
reclst[i]['Score'] = ps
reclst[i]['Rank'] = pr
f = open('sports.dat','wb')
for i in reclst:

Delete the record

Deleting a record is a little bit tricky. Just we are overwriting contents except for the record which is asked to be deleted. Let’s have look at these steps:
    1. Open the file in reading mode
    2. Load data using the load function
    3. Close file
    4. Prompt a message to delete a record with a variable
    5. Open file in writing mode
    6. Declare a list object to store data from the file
    7. Use for loop and if condition as used in the update
    8. Now in if condition write continue if the record is found
    9. Write data using the dump method
    10. Close the file

Observe this code (Assume the Pickle module is included):

def bf_delete():
   f = open('sports.dat','rb')
reclst = []
while True:
rec = pickle.load(f)
except EOFError:
pc=int(input("Enter Player code to delete record:"))
f = open('sports.dat','wb')
for i in reclst:
if i['Pcode']==pc:
f.close() bf_delete()

Download the complete program

Follow the below-given link to download the complete program.

Download Binary File Menu Driven Binary File program

Thank you for reading this article. Feel free to ask any doubt in the comment section or via the contact us form.

3 thoughts on “File handling – Binary file operations in Python – Search, Append, Update and Delete Records”
  1. In the last delete function. My question is -will the record be displayed on output or not

  2. i was just thinking that when we update a record and dump it in file at the required location than the record which is previously written and is present at that location is overwritten by new one??
    plz clear my doubt

Leave a Reply

Your email address will not be published. Required fields are marked *