Python: Search strings in a file and get line numbers of lines containing the string

Search strings in a file and get line numbers of lines containing the string in Python.

In this article we will discuss how to search strings in a file and get all the lines and line numbers which will match or which contains the string.

Searching string in a file is easily accomplished by python. And we can easily get the line numbers of lines containing the string.

 Check if string is present in file or not  :

First take a file named “example.txt”

This is an example for sample file
Programming needs logic.
Languages are of many types.
Computer science is a study of computers & computational systems.
We can write a program in any language.
The end

Let’s see the program for it.

#Program :

# create a function to check the string is present in the file or not
def string_in_file(file_name, string_to_search):

  #Checking if any line in the metioned file contains given string or not
  # Open the file in read only mode to read content of the file
  with open(file_name, 'r') as read_obj:

  # Reading all lines in the file one by one by iteration
  for line in read_obj:
  # For each line, checking if the line contains the string or not
    if string_to_search in line:
      return True
  return False



#checking if string 'is' is found in file 'sample.txt'
if string_in_file('sample.txt','is'):
  print('string found')
else:
  print('string not found')
Output:
string found

Here, we use loop for iteration to check each line whether the string is present or not. If the line contains the string then it will return True and if the line does not contain the string then it will return False.

Search for a string in file & get all lines containing the string along with line numbers :

Suppose we have a file named “example.txt”

This is an example for sample file
Programming needs logic.
Languages are of many types.
Computer science is a study of computers & computational systems.
We can write a program in any language.
The end
#Program :

def string_in_file(file_name, string_to_search):
    #Searching for the given string in file along with its line numbers
    line_number = 0
    list_of_results = []
    # Opening the file in read only mode
    with open(file_name, 'r') as read_obj:
        # Reading all lines in the file one by one by iterating the file
        for line in read_obj:
            # checking each line, if the line contains the string
            line_number += 1
            if string_to_search in line:
                # If it contains the string, then add the line number & line as a tuple in the list
                list_of_results.append((line_number, line.rstrip()))
    # Return list of tuples containing line numbers and lines where string is found
    return list_of_results


lines = string_in_file('example.txt', 'is')
print('Total Matched lines : ', len(lines))
for i in lines:
    print('Line Number = ', i[0], ' :: Line = ', i[1])
Output:
Total Matched lines : 2
Line Number =  1  :: Line =  This is an example for sample file
Line Number =  4  :: Line =  Computer science is a study of computers & computational systems.

Here, we use loop for iteration to check each line whether the string is present or not. If the line contains the string then it will return True and if the line does not contain the string then it will return False.

We tried to print the total number of matched lines which consist of the string ‘is’. In total, there where two lines, which include the string ‘is’ and this function returned those lines along with their line numbers. Now instead of searching single string we want to search multiple string.

Search for multiple strings in a file and get lines containing string along with the line numbers :

To search for multiple string in a file, we have to create a separate function, that will open a file once and then search for the lines in the file which contains the given string. Because we cannot use the above created function because this will open and close the file for each string.

Suppose we have a file named “example.txt”

This is an example for sample file
Programming needs logic.
Languages are of many types.
Computer science is a study of computers & computational systems.
We can write a program in any language.
The end
#Program :

def strings_in_file(file_name, list_of_strings):
    #Here getting line from the file along with line numbers
    #which contains any of the matching string from the list
    line_number = 0
    list_of_results = []
    # Opening the file in read only mode
    with open(file_name, 'r') as read_obj:
        # Reading all lines in the file one by one by iteration
        for line in read_obj:
            line_number += 1
            # Checking each line, if the line contains any string from the list of strings
            for string_to_search in list_of_strings:
                if string_to_search in line:
                    # If any string is matched/found in line
                    # then we will append that line along with line number in the list
                    list_of_results.append((string_to_search, line_number, line.rstrip()))
    # Returning the list of tuples containing matched string, line numbers and lines where string is found
    return list_of_results

#Now, we will use this function

# search for given strings in the file 'sample.txt'
matched_lines = strings_in_file('sample.txt', ['is', 'what'])
print('Total Matched lines : ', len(matched_lines))
for elem in matched_lines:
    print('Word = ', elem[0], ' :: Line Number = ', elem[1], ' :: Line = ', elem[2])

Output:
Total Matched lines : 2
Word = 'is' :: Line Number =  1  :: Line =  This is an example for sample file
Word = 'is' :: Line Number =  4  :: Line =  Computer science is a study of computers & computational systems.

Here, we use loop for iteration to check each line whether the string is present or not. If the line contains the string then it will return True and if the line does not contain the string then it will return False.

Leave a Comment