Home »
Python »
Python programs
Check if the record is present in the file using its id in Python
Here, we are going to learn how to check if the record is present in the file using its id in Python?
Submitted by Shivang Yadav, on February 11, 2021
Description: 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.
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'.
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'.
Python file handling programs »