Computer Science, asked by prasoon2honey, 7 months ago

write a python function to search for a particular data in binary file product.data based on pno and display the details of the product

Answers

Answered by GamerAzim
0

# Python program to search for a particular data in any given binary file

 

def update_binary(word, new)  

   # string variable to store  

   # each word after reading  

   # from the file  

   string = b""  

 

   # Flag variable to check  

   # if the record is found or  

   # not  

   Flag = 0

 

   # Open the file in r + b mode which means  

   # opening a binary file for reding and  

   # writing  

   with open('file.txt', 'r + b') as file:  

 

       pos = 0

 

       # Reading the content of the  

       # file character by character  

       data = string = file.read(1)  

 

       # Looping till the end of  

       # file is reached  

       while data:  

           data = file.read(1)  

 

           # Checking if the space is reached  

           if data == b" ":  

 

               # checking the word read with  

               # the word entered by user  

               if string == word:  

 

                   # Mpving the file pointer  

                   # at the end of the previously  

                   # read record  

                   file.seek(pos)  

 

                   # Updating the content of the file  

                   file.write(new)  

                   Flag = 1

                   break

               else:  

                   # storing the position of  

                   # current file pointer i.e. at  

                   # the end of previously read record  

                   pos = file.tell()  

                   data = string = file.read(1)  

           else:  

 

               # Storing the data of the file  

               # in the string variable  

               string += data  

               continue

 

 

   if Flag:  

       print("Record successfully updated")  

   else:  

       print("Record not found")  

         

         

# Dirver's code  

# Input the word to be found  

# and the new word  

word = input("Enter the word to be replaced: ").encode()  

new = input("\nEnter the new word: ").encode()  

 

update_binary(word, new)

Answered by allysia
1

Language:

Python

Program:

#assuming the file is in [Pno, P_Name, Quantity, Price] format

def search():

   import pickle

   file=open('product.dat', 'br')

   read=pickle.load(file)

   pno=input("Enter the product number: ")

   for i in read:

       if i[0]==pno:

           print(i)

   file.close()

search()

Explanation:

  • pickle module helps to perform operations on binary files here it's load i.e to read the file.
  • Using for loop we check if the user inputted  product number exists in the file or not. If it does, we print it on the screen.
Similar questions