Your approach is a good starting point. Depending on exactly what sort of file you are reading and its contents (which isn't specified), there are a few approaches which may work:
str
:check_if_string_in_file(file_name, str(123))
Note that this approach falls short if e.g. your file has a line like "12345", as '123' in '12345'
is true. You can resolve this by using a more strict check (instead of just in
).
int
function:def check_if_string_in_file(file_name, number_to_search):
with open(file_name, 'r') as read_obj:
for line in read_obj:
line_as_int = int(line.strip())
if number_to_search == line_as_int:
return True
return False
If you plan to do several such checks, it may make sense to read the whole file into a list in one shot and then check for the target in the list.