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

Python | Check if the record is present in the file: In this tutorial, we will learn how to check if the record is present in the file using its id i.e., based on the given id. By Shivang Yadav Last updated : July 05, 2023

Here, we will see a program to check if the record is present in the file or not using its id in python.

Problem Statement

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.

Checking if the record is present in the file using its id

Steps to check if the specific contents entered by the user of file are as follows,

  • 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'.

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

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

Python file handling programs »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.