Find line number of a specific string or substring or word from a .txt file in Python

In this tutorial, we are going to learn how to find location of one or many strings in terms of line numbers in a text file using Python.
For instance let us assume we want to find the string/keyword “Codespeedy” from the example text file that is as shown below:

Example.txt

This is a sample text file.
Codespeedy Technology Private Limited is an Information technology company that keeps
helping the learners and developers to learn computer programming. Codespeedy also 
provides coding solutions along with various IT services ( web development, software
development etc ). Codespeedy is a great place to learn programming concepts.

Creating a Python function that returns line number of the string from a text file:

def word_search(key, filename):
    with open(filename) as file:  # opening the file using with to ensure it closes after the block of code is executed
        lines = file.readlines()  # reading the lines of the file in order
    for line_number, line in enumerate(lines, 1):  # using enumerate to map each line of the file to it's line_number
        if key in line:  # searching for the keyword in file
            return line_number  # returning the line number

keyword = input("Enter the word you wish to search from the Example.txt textfile:\n")
print(f'''The keyword {keyword} is found at line number {word_search(keyword,'Rxample.txt\n')}''')

Output:

Enter the word you wish to search from the Example.txt textfile:
Codespeedy
The keyword Codespeedy is found at line number 2

Here we have used readlines() method to read the text file line wise. Enumerate function has been used to map the lines to their corresponding line numbers.

Finding multiple iterations of the same string in a text file:

Considering the same text file mentioned above if we want to find all the iterations of the string(keyword) “Codespeedy” from the text file we can make slight changes to above the function to obtain the line numbers of the lines in which the keyword/string is present.

def word_search(key, filename):
    with open(filename) as file:  # opening the file using with to ensure it closes after the block of code is executed
        lines = file.readlines()  # reading the lines of the files in order
    for number, line in enumerate(lines, 1):  # using enumerate to map each line of the file to it's line_number
        if key in line:  # searching for the keyword in file
            print(f'{key} is in the line {number}')  # returning the line number if the keyword

keyword = input("Enter the string/keyword you wish to search:")  # user input of the keyword
word_search(keyword,'Example.txt')

Output:

Enter the string/keyword you wish to search:
Codespeedy
Codespeedy is in the line 2
Codespeedy is in the line 3
Codespeedy is in the line 5

Finding several different keywords/strings in a text file:

Considering the same text file mentioned above if we want to find several keywords/strings in a text file we can use same function mentioned above to obtain the line numbers of the lines in which these keywords/strings are present.

def word_search(key, filename):
    with open(filename) as file:  # opening the file using with to ensure it closes after the block of code is executed
        lines = file.readlines()  # reading the lines of the files in order
    for number, line in enumerate(lines, 1):  # using enumerate to map each line of the file to it's line_number
        if key in line:  # searching for the keyword in file
            print(f'{key} is in the line {number}')  # returning the line number

strings = input("Enter all the strings use to wish to search separated by space:\n")
string_list = list(strings.split())
for item in string_list:
    word_search(item,'Example.txt')

Output:

Enter all the strings use to wish to search separated by space:
Codespeedy developers
Codespeedy is in the line 2
Codespeedy is in the line 3
Codespeedy is in the line 5
developers is in the line 3

In this program split() method has been used to split the incoming input string separated by spaces into individual words.

3 responses to “Find line number of a specific string or substring or word from a .txt file in Python”

  1. Spandana says:

    Good stuff! Very good explanation
    Looking forward to more and more articles!
    Keep it up!
    Yayyy

  2. Shashank S Hegde says:

    Thank you Codespeedy for explaining this in simple terms . Really it is very useful article to me .

  3. Shruti says:

    This is great!
    It was easily understandable.

Leave a Reply

Your email address will not be published. Required fields are marked *