How to search for a string in text files?

后端 未结 12 2276
死守一世寂寞
死守一世寂寞 2020-11-22 04:29

I want to check if a string is in a text file. If it is, do X. If it\'s not, do Y. However, this code always returns True for some reason. Can anyone see what i

12条回答
  •  既然无缘
    2020-11-22 05:34

    As Jeffrey Said, you are not checking the value of check(). In addition, your check() function is not returning anything. Note the difference:

    def check():
        with open('example.txt') as f:
            datafile = f.readlines()
        found = False  # This isn't really necessary
        for line in datafile:
            if blabla in line:
                # found = True # Not necessary
                return True
        return False  # Because you finished the search without finding
    

    Then you can test the output of check():

    if check():
        print('True')
    else:
        print('False')
    

提交回复
热议问题