How to search for a string in text files?

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

    Two problems:

    1. Your function does not return anything; a function that does not explicitly return anything returns None (which is falsy)

    2. True is always True - you are not checking the result of your function

    .

    def check(fname, txt):
        with open(fname) as dataf:
            return any(txt in line for line in dataf)
    
    if check('example.txt', 'blabla'):
        print "true"
    else:
        print "false"
    

提交回复
热议问题