Table of Contents
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
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.
0 Comments