Search a Word in Text File – Python Way

Searching a word in a text file in languages like C/C++/Java needs a lot of effort. These languages, first of all, force us to read a word/line/ and then compare each word. These methods are old fashioned and now need little bit modification.

as a python learner tried to solve the same issue using python way. Here is python code to search a word in a text file, later I will try to explain each line.

#   python program to search a word in a text File
#   program by          : rakesh kumar

word = input('Enter any word that you want to find in text File :')
f = open("rakesh.txt","r")
if word in f.read().split():
    print('Word Found in Text File')
else:
    print('Word not found in Text File')

The content of the rakesh.txt file is as follows. This file has been stored in the same directory.

Hello rakesh how are you 
i am trying to search a word in this file 
using python and file handling in python.

The output of the search a word in text file is as follows

as@DESKTOP-P84OH09 MINGW64 ~/desktop
$ c:/python37/python.exe c:/Users/as/Desktop/Search_in_file.py
Enter any word that you want to find in text File :python
Word Found in Text File

Line no 1 simply asked user to feed any word from the keyboard, the second line is responsible to open your text file in text mode.

line no 3 is the most important line, first of all, we are reading the content of the whole file and then using split() function converted the content of that whole file in a LIST.  The same list content was compared using an IN operator.

One of my reader pointed out that the above program will not be able to search terms like “India”  Here is the modified text file that contains the term in double inverted quotes.

Hello rakesh how are you 
i am trying to search a word in this file 
I love "India" . Do you love ??
using python and file handling in python.

so modified the above program a little bit and  here is the solution

#   python program to search a word in a text File
#   program by          : rakesh kumar

word = input('Enter any word that you want to find in text File :')
word1= '"'+word+'"'
word2= "'"+word+"'"
f = open("rakesh.txt","r")
data = f.read().split()
if word in data or word1 in data or word2 in data:
    print('Word Found in Text File')
else:
    print('Word not found in Text File')

Hope you will like this simple program to search any word in a text file, If you have any doubt/query, please let us know via your comments.

Related Posts

If you like CBSEToaday and would like to contribute, you can also write an article using submit article or mail your article to contribute@cbsetoday.com See your article appearing on the cbsetoday.com main page and help other students/teachers.