Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
130 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...