Open In App

How to obtain the line number in which given word is present using Python?

Last Updated : 04 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

To obtain the line number from the file where the given word is present, create a list in which each index contains the content of each line with Python. To do so follow the below instruction.

Get Line Number of Certain Phrase in a Text file

Below are the methods that we will cover in this article.

  • Using Iteration
  • Using Enumerate

Input file: File1.txt

Screenshot-2023-08-02-114506

File1.txt

Get line number in which the given word is present through Iteration

Here we can obtain the line number in which a given word is present in a file using Python by reading the file line by line and keeping track of the line number where the word is found and below is an example code for that. In which we iterate over every element using for loop and keep track by a variable line_number so that when we encounter the word we have the line_number of the line in which that word is present.

Python3




def find_word_line_number(filename, target_word):
    line_number = 0
 
    with open(filename, 'r') as file:
        for line in file:
            line_number += 1
            if target_word in line:
                return line_number
 
    # If the word is not found in the file, return None
    return None
 
# Example usage
filename = "File1.txt"  # Replace with the name of your file
word_to_find = "hello"    # Replace with the word you want to find
line_number = find_word_line_number(filename, word_to_find)
if line_number is not None:
    print(f"The word '{word_to_find}' is present in line number: {line_number}")
else:
    print(f"The word '{word_to_find}' is not found in the file.")


Output: 

The word 'Romy' is present in line number: 1

Time complexity: O(1)
Auxiliary space: O(n) where n is the size of the file as the entire file is being read and stored in the variable “read”.

Obtain the line number in which the given word is present through Enumerate

Here we have another method to obtain the line in which a given word is present with the help of enumerate() a function in Python. With the help of this method, it allows us to iterate over lines of the file along with their line number directly, and when we find the word which matches the word in the input we print the word and line in which we find it.

Python3




def find_word_in_file(file_path, target_word):
    try:
        with open(file_path, 'r') as file:
            for line_number, line in enumerate(file, start=1):
                if target_word in line:
                    return line_number
 
    except FileNotFoundError:
        print("Error: The file was not found.")
    except Exception as e:
        print(f"An error occurred: {e}")
 
    return None  # Return None if the word is not found in the file.
 
 
# Example usage:
file_path = 'file1.txt'
word_to_find = 'Abhishek'
result = find_word_in_file(file_path, word_to_find)
if result:
    print(f"The word '{word_to_find}' was found in line number: {result}")
else:
    print(f"The word '{word_to_find}' was not found in the file.")


Output:

The word 'Abhishek' was not found in the file.

Time complexity: O(1)
Auxiliary space: O(n) where n is the size of the file as the entire file is being read and stored in the variable “read”.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads