I want to search for a number in a text file but whatever I enter gives me the output "The number is not in the list"
I'm a beginner by the way so this code might make some people cringe.
searchfile = open("searching.txt", "r")
condition = 0
b = input("enter a number to search ")
for line in searchfile.readlines():
if b in line:
condition = True
else:
condition = False
if condition == True:
print ("The number is in the list")
else:
print ("The number is not in the list")
searchfile.close()
CodePudding user response:
Just as mentioned in the comments, your code checks if the number is part of the last string. I would suggest the following structure:
def is_number_in_line(number: str, line: str) -> bool:
return number in line
number = input("enter a number to search \n")
condition = False
with open("searching.txt") as f:
lines = f.readlines()
for line in lines:
if is_number_in_line(number, line):
condition = True
break
if condition:
print("The number is in the list")
else:
print("The number is not in the list")
Also, note that "1" is part of the string "312 Main St", but the string does not really contain "1" as a number. You may want to modify is_number_in_line
accordingly.
CodePudding user response:
def numInfile():
searchfile = open("searching.txt", "r")
b = input("enter a number to search ")
for line in searchfile.readlines():
if b in line:
print ("The number is in the list")
return
print ("The number is not in the list")