File Handling - Binary File Operations In Python - Search, Append, Update And Delete Records | TutorialAICSIP (2024)

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:

  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:")) 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:

  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("*"*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:

    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:")) 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:

    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:
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:

    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:
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.

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.

Related

File Handling - Binary File Operations In Python - Search, Append, Update And Delete Records | TutorialAICSIP (2024)
Top Articles
Oasis Network verwachting, wat gaat de ROSE crypto doen?
Activity-Based Costing (ABC): Method and Advantages Defined with Example
Katie Pavlich Bikini Photos
Gamevault Agent
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Free Atm For Emerald Card Near Me
Craigslist Mexico Cancun
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Doby's Funeral Home Obituaries
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Select Truck Greensboro
How To Cut Eelgrass Grounded
Pac Man Deviantart
Craigslist In Flagstaff
Shasta County Most Wanted 2022
Energy Healing Conference Utah
Testberichte zu E-Bikes & Fahrrädern von PROPHETE.
Aaa Saugus Ma Appointment
Geometry Review Quiz 5 Answer Key
Walgreens Alma School And Dynamite
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
Dmv In Anoka
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Pixel Combat Unblocked
Umn Biology
Cvs Sport Physicals
Mercedes W204 Belt Diagram
Rogold Extension
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Weekly Math Review Q4 3
Facebook Marketplace Marrero La
Nobodyhome.tv Reddit
Topos De Bolos Engraçados
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Holzer Athena Portal
Hampton In And Suites Near Me
Stoughton Commuter Rail Schedule
Bedbathandbeyond Flemington Nj
Free Carnival-themed Google Slides & PowerPoint templates
Otter Bustr
San Pedro Sula To Miami Google Flights
Selly Medaline
Latest Posts
Article information

Author: Greg O'Connell

Last Updated:

Views: 6213

Rating: 4.1 / 5 (62 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Greg O'Connell

Birthday: 1992-01-10

Address: Suite 517 2436 Jefferey Pass, Shanitaside, UT 27519

Phone: +2614651609714

Job: Education Developer

Hobby: Cooking, Gambling, Pottery, Shooting, Baseball, Singing, Snowboarding

Introduction: My name is Greg O'Connell, I am a delightful, colorful, talented, kind, lively, modern, tender person who loves writing and wants to share my knowledge and understanding with you.