Q:

Check if the record is present in the file using its id in Python

belongs to collection: Python file handling programs

0

 Python program to check if the record is present in the file using its id.

Problem Description: We need to find the data from the file whose id is the same as the id entered by the user.

We will use the concepts of file handling in python.

Steps to check if the specific contents entered by the user of file:

  • Step 1: Open the file in append mode using 'r'.
  • Step 2: Get the input data from the user.
  • Step 3: Compare the inputted data with data from file.
    • Step 3.1: if data is present, print it.
    • Step 3.2: if data is absent, print 'Record Not Found'.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program to illustrate the solution of the problem

F=open("data.dat","r")

id=input("Enter Id:")

found=False

while(True):
    data=F.readline()
    if(data==""):
        break
    
    DL=data.split(",")
    if(DL[0]==id):
        DL[2]=DL[2].rstrip("\n")
        DL.append(int(DL[2])*20/100)
        print(DL)
        found=True
        break
if(not found):
    print("Record Not Found")

F.close()

Output:

Enter Id:10323
['10323', 'Ram', '50000', 10000.0]

Here, we have opened data using 'r' mode. After this, we have requested the user for an input id to be searched for. Then we have compared the id's of data in the file. If any id matches, we will print its data otherwise print 'Record Not Found'.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Copy contents from one file to another file in Pyt... >>
<< Read contents of the file using readlines() method...