How to search for a string in text files?

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

    I made a little function for this purpose. It searches for a word in the input file and then adds it to the output file.

    def searcher(outf, inf, string):
        with open(outf, 'a') as f1:
            if string in open(inf).read():
                f1.write(string)
    
    • outf is the output file
    • inf is the input file
    • string is of course, the desired string that you wish to find and add to outf.

提交回复
热议问题