How to search for a string in text files?

后端 未结 12 2278
死守一世寂寞
死守一世寂寞 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:23

    Your check function should return the found boolean and use that to determine what to print.

    def check():
            datafile = file('example.txt')
            found = False
            for line in datafile:
                if blabla in line:
                    found = True
                    break
    
            return found
    
    found = check()
    if found:
        print "true"
    else:
        print "false"
    

    the second block could also be condensed to:

    if check():
        print "true"
    else:
        print "false"
    

提交回复
热议问题