Program to get line number in which given word is present using Python

Introduction

The task is to search the word in text file and print the line numbers is it present.

Program

openFile = open("demo.txt") 
readFile = openFile.read() 
openFile.seek(0) 
temp, x = [] , 1 
for searchedWord in readFile: 
    if searchedWord == '\n': 
        x += 1
print("Total number of lines: ", x)   
for y in range(x):  
    temp.append(openFile.readline()) 
def search(searchedWord): 
    for y in range(len(temp)): 
        if searchedWord in temp[y]: 
            print(y+1) 
    
search("Python")

Output

Program to get line number in which given word is present using Python

Explanation

Approach:

  • Create a list to store the text of each lines in index format.
  • Traverse through the indexes and check for the searched word.
    • Return the index+1 if word is present.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.