How to search for a string in text files?

后端 未结 12 2291
死守一世寂寞
死守一世寂寞 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条回答
  •  -上瘾入骨i
    2020-11-22 05:09

    Here's another. Takes an absolute file path and a given string and passes it to word_find(), uses readlines() method on the given file within the enumerate() method which gives an iterable count as it traverses line by line, in the end giving you the line with the matching string, plus the given line number. Cheers.

      def word_find(file, word):
        with open(file, 'r') as target_file:
            for num, line in enumerate(target_file.readlines(), 1):
                if str(word) in line:
                    print(f' {line}')
                else:
                    print(f'> {word} not found.')
    
    
      if __name__ == '__main__':
          file_to_process = '/path/to/file'
          string_to_find = input()
          word_find(file_to_process, string_to_find)
    

提交回复
热议问题