Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
110 views
in Technique[技术] by (71.8m points)

python - How do I check for an integer in a text file?


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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...