-3

I have a text file to save data and I put many numbers in the text file for example


how do I check if the given number is already exists in the text file??


I tried many different ways like:

def check_if_string_in_file(file_name, string_to_search):
    with open(file_name, 'r') as read_obj:
        for line in read_obj:
            if string_to_search in line:
                return True
    return False

But in this case the string_to_search can not be integer

ELAi
  • 170
  • 2
  • 8

2 Answers2

-1

In your example, string_to_search can be converted from an int to its str representation using str():

def check_if_string_in_file(file_name, string_to_search):
    with open(file_name, 'r') as read_obj:
        for line in read_obj:
            if str(string_to_search) in line:
                return True
    return False

if string_to_search is already a str, it will have no effect.

JoshuaMK
  • 104
  • 1
  • 6
-1

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:

  1. Before calling your function with an integer value, convert it to a string with 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).

  1. If you know that all the lines in your file will just be numbers, you can convert the line to number after reading it in using the 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.

Alex
  • 632
  • 3
  • 11