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:
Topics Covered
Append data in Binary File
To append data in binary follow these steps:
- Open the file in append mode using “ab” Ex.: f = open (“file.dat”,”ab”)
- Enter data to append
- Append entered data into the dictionary/list object
- Use pickle.dump() method to write the dictionary/list data
- 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:")) rec={'Pcode':pcode,'Pname':pname,'Score':score,'Rank':rank} pickle.dump(rec,f) f.close()bf_append()
Do not run your code without reading the contents.
Reading Data
Follow these steps to read data:
- Open the file in read mode using “rb” Ex.: f = open(“File.dat”, “rb”)
- Use while loop with True statement to read the entire contents of the file individually.
- Use try – except for Exception handling to avoid runtime EOFError
- Now load data into an object through the load function
- Print data as per need
- Close the file
Observe the following code:
def bf_read(): f = open("Sports.dat","rb") print("*"*78) 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:
- Open the file in reading mode using “rb”
- Prompt a message to ask unique field from data to search
- Declare a boolean variable flag to store False for the record not found and True when the record found
- Use a while loop to access records individually
- Now load the data into the dictionary object using load() function
- Use if condition to compare the data with the variable taken in step 2
- Print the record found
- Assign True to the flag variable declared in step 3
- Use the except block to handle EOFError and terminate the loop using the break
- Print record not found message when Flag is False
- 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:")) flag=False 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:
- Open the file using read mode
- Declare a variable for unique value to be updated
- Use try-except and while loop as explained above
- Add record fetched from binary file into a list
- Enter the new record information to update
- Compare the fetched records with entered record and assign the new values to update
- Write the data using dump() function
- Close the file
Have look at the following code:
def bf_update():
f = open('student.dat','rb')
reclst = []
while True:
try:
rec = pickle.load(f)
reclst.append(rec)
except EOFError:
break
f.close()
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:
pickle.dump(i,f)
f.close()
bf_update()
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:
- Open the file in reading mode
- Load data using the load function
- Close file
- Prompt a message to delete a record with a variable
- Open file in writing mode
- Declare a list object to store data from the file
- Use for loop and if condition as used in the update
- Now in if condition write continue if the record is found
- Write data using the dump method
- Close the file
Observe this code (Assume the Pickle module is included):
def bf_delete(): f = open('sports.dat','rb')
reclst = []
while True:
try:
rec = pickle.load(f)
reclst.append(rec)
except EOFError:
break
f.close()
pc=int(input("Enter Player code to delete record:"))
f = open('sports.dat','wb')
for i in reclst:
if i['Pcode']==pc:
continue
pickle.dump(x,f)
f.close() bf_delete()
Download the complete program
Follow the below-given link to download the complete program.
Thank you for reading this article. Feel free to ask any doubt in the comment section or via the contact us form.