
Line Number = 6 :: Line = This is the end of file Line Number = 1 :: Line = Hello this is a sample file Print('Line Number = ', elem, ' :: Line = ', elem) Print('Total Matched lines : ', len(matched_lines)) Matched_lines = search_string_in_file('sample.txt', 'is') Let’s get all the line along with line numbers which contain the word ‘ is’, Suppose we have a file ‘sample.txt’ and its contents are, Return the list of tuples i.e., matched lines along with line numbers.Creates a tuple of line number & the line and adds that to a list of tuples.For each line, check if it contains the given string or not.Iterates over each line in the file one by one.Open the file at the given path in read-only mode.Accept arguments – file path and a string to lookup.In the end, it returns a list of tuples, where each tuple contains the line number and line, which includes the given string. It accepts a file path and a string as arguments. # Return list of tuples containing line numbers and lines where string is found List_of_results.append((line_number, line.rstrip())) # If yes, then add the line number & line as a tuple in the list """Search for the given string in file and return lines containing that string, We have created a function, to get all the lines and line numbers which contain the given string,ĭef search_string_in_file(file_name, string_to_search):
#How to make line numbers in word how to#
Let’s see how to do that, Search for a string in file & get all lines containing the string along with line numbers But what if we want to know all the exact occurrences of a string in the file like lines and line numbers. Here we get to know that file contains the given string or not. If check_if_string_in_file('sample.txt', 'is'):Īs file contains the ‘ is’, therefore function check_if_string_in_file() returns True. # Check if string 'is' is found in file 'sample.txt' Let’s check if this file contains a string ‘ is’ or not, Whereas if no line in the file contains the given string, then it returns False.

If the line contains the given string, then return True. Then iterates over each line in the file one by one and for each line check if it contains the given string or not. # For each line, check if line contains the string

""" Check if any line in the file contains given string """ To check if a given string exists in the file or not, we have created a function,ĭef check_if_string_in_file(file_name, string_to_search):

In this article, we are going to discuss, how to search for single or multiple strings in a file and get all the matched lines along with their line numbers.
