8

I'm working with Python, and I'm trying to find out if a word is in a text file. i am using this code but it always print the "word not found", i think there is some logical error in the condition, anyone please if you can correct this code:

file = open("search.txt")
    print(file.read())
    search_word = input("enter a word you want to search in file: ")
    if(search_word == file):
        print("word found")
    else:
        print("word not found")
  • 1
    search_word in a file, not equal to the file. – zhenguoli May 26 '17 at 16:11
  • Try this https://stackoverflow.com/questions/4940032/search-for-string-in-txt-file-python – manvi77 May 26 '17 at 16:14
  • `print(file.read())` reads the file contents into a string, prints it, then throws it away. You don't want to do that. You need to save the file data, eg `data = file.read()`. And you should read about Python's `in` operator. – PM 2Ring May 26 '17 at 16:14
  • @zhenguoli so than what should be the correct condition there ? –  May 26 '17 at 16:15

3 Answers3

13

Better you should become accustomed to using with when you open a file, so that it's automatically close when you've done with it. But the main thing is to use in to search for a string within another string.

with open('search.txt') as file:
    contents = file.read()
    search_word = input("enter a word you want to search in file: ")
    if search_word in contents:
        print ('word found')
    else:
        print ('word not found')
Bill Bell
  • 21,021
  • 5
  • 43
  • 58
5

Other alternative, you can search while reading a file itself:

search_word = input("enter a word you want to search in file: ")

if search_word in open('search.txt').read():
    print("word found")
else:
    print("word not found")

To alleviate the possible memory problems, use mmap.mmap() as answered here related question

manvi77
  • 536
  • 1
  • 5
  • 15
3

Previously, you were searching in the file variable, which was 'open("search.txt")' and since that wasn't in your file, you were getting word not found.

You were also asking if the search word exactly matched 'open("search.txt")' because of the ==. Don't use ==, use "in" instead. Try:

file = open("search.txt")
strings = file.read()
print(strings)
search_word = input("enter a word you want to search in file: ")
if(search_word in strings):
    print("word found")
else:
    print("word not found")
Harvey Fletcher
  • 1,167
  • 1
  • 9
  • 22