{"id":5040,"date":"2023-10-26T15:53:08","date_gmt":"2023-10-26T10:23:08","guid":{"rendered":"https:\/\/python-programs.com\/?p=5040"},"modified":"2023-11-10T12:00:20","modified_gmt":"2023-11-10T06:30:20","slug":"python-search-strings-in-a-file-and-get-line-numbers-of-lines-containing-the-string","status":"publish","type":"post","link":"https:\/\/python-programs.com\/python-search-strings-in-a-file-and-get-line-numbers-of-lines-containing-the-string\/","title":{"rendered":"Python: Search strings in a file and get line numbers of lines containing the string"},"content":{"rendered":"

Search strings in a file and get line numbers of lines containing the string in Python.<\/h2>\n

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.<\/p>\n

Searching string in a file is easily accomplished by python. And we can easily get the line numbers of lines containing the string.<\/p>\n

\u00a0Check if string is present in file or not\u00a0 :<\/h3>\n

First take a file named \u201cexample.txt\u201d<\/code><\/p>\n

This is an example for sample file\r\nProgramming needs logic.\r\nLanguages are of many types.\r\nComputer science is a study of computers & computational systems.\r\nWe can write a program in any language.\r\nThe end<\/pre>\n

Let’s see the program for it.<\/p>\n

#Program :\r\n\r\n# create a function to check the string is present in the file or not\r\ndef string_in_file(file_name, string_to_search):\r\n\r\n  #Checking if any line in the metioned file contains given string or not\r\n  # Open the file in read only mode to read content of the file\r\n  with open(file_name, 'r') as read_obj:\r\n\r\n  # Reading all lines in the file one by one by iteration\r\n  for line in read_obj:\r\n  # For each line, checking if the line contains the string or not\r\n    if string_to_search in line:\r\n      return True\r\n  return False\r\n\r\n\r\n\r\n#checking if string 'is' is found in file 'sample.txt'\r\nif string_in_file('sample.txt','is'):\r\n  print('string found')\r\nelse:\r\n  print('string not found')<\/pre>\n
Output:\r\nstring found<\/pre>\n

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.<\/p>\n

Search for a string in file & get all lines containing the string along with line numbers :<\/h3>\n

Suppose we have a file named \u201cexample.txt\u201d<\/code><\/p>\n

This is an example for sample file\r\nProgramming needs logic.\r\nLanguages are of many types.\r\nComputer science is a study of computers & computational systems.\r\nWe can write a program in any language.\r\nThe end<\/pre>\n
#Program :\r\n\r\ndef string_in_file(file_name, string_to_search):\r\n    #Searching for the given string in file along with its line numbers\r\n    line_number = 0\r\n    list_of_results = []\r\n    # Opening the file in read only mode\r\n    with open(file_name, 'r') as read_obj:\r\n        # Reading all lines in the file one by one by iterating the file\r\n        for line in read_obj:\r\n            # checking each line, if the line contains the string\r\n            line_number += 1\r\n            if string_to_search in line:\r\n                # If it contains the string, then add the line number & line as a tuple in the list\r\n                list_of_results.append((line_number, line.rstrip()))\r\n    # Return list of tuples containing line numbers and lines where string is found\r\n    return list_of_results\r\n\r\n\r\nlines = string_in_file('example.txt', 'is')\r\nprint('Total Matched lines : ', len(lines))\r\nfor i in lines:\r\n    print('Line Number = ', i[0], ' :: Line = ', i[1])\r\n<\/pre>\n
Output:\r\nTotal Matched lines : 2\r\nLine Number =\u00a0 1\u00a0 :: Line =\u00a0 This is an example for sample file\r\nLine Number =\u00a0 4\u00a0 :: Line =\u00a0 Computer science is a study of computers & computational systems.<\/pre>\n

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.<\/p>\n

We tried to print the total number of matched lines which consist of the string \u2018is\u2019. In total, there where two lines, which include the string \u2018is\u2019 and this function returned those lines along with their line numbers. Now instead of searching single string we want to search multiple string.<\/p>\n

Search for multiple strings in a file and get lines containing string along with the line numbers :<\/h3>\n

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.<\/p>\n

Suppose we have a file named \u201cexample.txt\u201d<\/p>\n

This is an example for sample file\r\nProgramming needs logic.\r\nLanguages are of many types.\r\nComputer science is a study of computers & computational systems.\r\nWe can write a program in any language.\r\nThe end<\/pre>\n
#Program :\r\n\r\ndef strings_in_file(file_name, list_of_strings):\r\n    #Here getting line from the file along with line numbers\r\n    #which contains any of the matching string from the list\r\n    line_number = 0\r\n    list_of_results = []\r\n    # Opening the file in read only mode\r\n    with open(file_name, 'r') as read_obj:\r\n        # Reading all lines in the file one by one by iteration\r\n        for line in read_obj:\r\n            line_number += 1\r\n            # Checking each line, if the line contains any string from the list of strings\r\n            for string_to_search in list_of_strings:\r\n                if string_to_search in line:\r\n                    # If any string is matched\/found in line\r\n                    # then we will append that line along with line number in the list\r\n                    list_of_results.append((string_to_search, line_number, line.rstrip()))\r\n    # Returning the list of tuples containing matched string, line numbers and lines where string is found\r\n    return list_of_results\r\n\r\n#Now, we will use this function\r\n\r\n# search for given strings in the file 'sample.txt'\r\nmatched_lines = strings_in_file('sample.txt', ['is', 'what'])\r\nprint('Total Matched lines : ', len(matched_lines))\r\nfor elem in matched_lines:\r\n    print('Word = ', elem[0], ' :: Line Number = ', elem[1], ' :: Line = ', elem[2])\r\n\r\n<\/pre>\n
Output:\r\nTotal Matched lines : 2\r\nWord = 'is' :: Line Number =\u00a0 1\u00a0 :: Line =\u00a0 This is an example for sample file\r\nWord = 'is' :: Line Number =\u00a0 4\u00a0 :: Line =\u00a0 Computer science is a study of computers & computational systems.<\/pre>\n

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.<\/p>\n","protected":false},"excerpt":{"rendered":"

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. …<\/p>\n

Python: Search strings in a file and get line numbers of lines containing the string<\/span> Read More »<\/a><\/p>\n","protected":false},"author":9,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"spay_email":"","jetpack_publicize_message":"","jetpack_is_tweetstorm":false,"jetpack_publicize_feature_enabled":true},"categories":[5],"tags":[],"yoast_head":"\nPython: Search strings in a file and get line numbers of lines containing the string - Python Programs<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/python-programs.com\/python-search-strings-in-a-file-and-get-line-numbers-of-lines-containing-the-string\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Python: Search strings in a file and get line numbers of lines containing the string - Python Programs\" \/>\n<meta property=\"og:description\" content=\"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. … Python: Search strings in a file and get line numbers of lines containing the string Read More »\" \/>\n<meta property=\"og:url\" content=\"https:\/\/python-programs.com\/python-search-strings-in-a-file-and-get-line-numbers-of-lines-containing-the-string\/\" \/>\n<meta property=\"og:site_name\" content=\"Python Programs\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/btechgeeks\" \/>\n<meta property=\"article:published_time\" content=\"2023-10-26T10:23:08+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-11-10T06:30:20+00:00\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@btech_geeks\" \/>\n<meta name=\"twitter:site\" content=\"@btech_geeks\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Satyabrata Jena\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"5 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Organization\",\"@id\":\"https:\/\/python-programs.com\/#organization\",\"name\":\"BTech Geeks\",\"url\":\"https:\/\/python-programs.com\/\",\"sameAs\":[\"https:\/\/www.instagram.com\/btechgeeks\/\",\"https:\/\/www.linkedin.com\/in\/btechgeeks\",\"https:\/\/in.pinterest.com\/btechgeek\/\",\"https:\/\/www.youtube.com\/channel\/UC9MlCqdJ3lKqz2p5114SDIg\",\"https:\/\/www.facebook.com\/btechgeeks\",\"https:\/\/twitter.com\/btech_geeks\"],\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/python-programs.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/python-programs.com\/wp-content\/uploads\/2020\/11\/BTechGeeks.png\",\"contentUrl\":\"https:\/\/python-programs.com\/wp-content\/uploads\/2020\/11\/BTechGeeks.png\",\"width\":350,\"height\":70,\"caption\":\"BTech Geeks\"},\"image\":{\"@id\":\"https:\/\/python-programs.com\/#\/schema\/logo\/image\/\"}},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/python-programs.com\/#website\",\"url\":\"https:\/\/python-programs.com\/\",\"name\":\"Python Programs\",\"description\":\"Python Programs with Examples, How To Guides on Python\",\"publisher\":{\"@id\":\"https:\/\/python-programs.com\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/python-programs.com\/?s={search_term_string}\"},\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/python-programs.com\/python-search-strings-in-a-file-and-get-line-numbers-of-lines-containing-the-string\/#webpage\",\"url\":\"https:\/\/python-programs.com\/python-search-strings-in-a-file-and-get-line-numbers-of-lines-containing-the-string\/\",\"name\":\"Python: Search strings in a file and get line numbers of lines containing the string - Python Programs\",\"isPartOf\":{\"@id\":\"https:\/\/python-programs.com\/#website\"},\"datePublished\":\"2023-10-26T10:23:08+00:00\",\"dateModified\":\"2023-11-10T06:30:20+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/python-programs.com\/python-search-strings-in-a-file-and-get-line-numbers-of-lines-containing-the-string\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/python-programs.com\/python-search-strings-in-a-file-and-get-line-numbers-of-lines-containing-the-string\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/python-programs.com\/python-search-strings-in-a-file-and-get-line-numbers-of-lines-containing-the-string\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/python-programs.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Python: Search strings in a file and get line numbers of lines containing the string\"}]},{\"@type\":\"Article\",\"@id\":\"https:\/\/python-programs.com\/python-search-strings-in-a-file-and-get-line-numbers-of-lines-containing-the-string\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/python-programs.com\/python-search-strings-in-a-file-and-get-line-numbers-of-lines-containing-the-string\/#webpage\"},\"author\":{\"@id\":\"https:\/\/python-programs.com\/#\/schema\/person\/0f6d731bda7051ce3586f71299f391cd\"},\"headline\":\"Python: Search strings in a file and get line numbers of lines containing the string\",\"datePublished\":\"2023-10-26T10:23:08+00:00\",\"dateModified\":\"2023-11-10T06:30:20+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/python-programs.com\/python-search-strings-in-a-file-and-get-line-numbers-of-lines-containing-the-string\/#webpage\"},\"wordCount\":381,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/python-programs.com\/#organization\"},\"articleSection\":[\"Python\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/python-programs.com\/python-search-strings-in-a-file-and-get-line-numbers-of-lines-containing-the-string\/#respond\"]}]},{\"@type\":\"Person\",\"@id\":\"https:\/\/python-programs.com\/#\/schema\/person\/0f6d731bda7051ce3586f71299f391cd\",\"name\":\"Satyabrata Jena\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/python-programs.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/c1bf8033ec357d085f41815bee1625cc?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/c1bf8033ec357d085f41815bee1625cc?s=96&d=mm&r=g\",\"caption\":\"Satyabrata Jena\"},\"url\":\"https:\/\/python-programs.com\/author\/satyabrata\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Python: Search strings in a file and get line numbers of lines containing the string - Python Programs","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/python-programs.com\/python-search-strings-in-a-file-and-get-line-numbers-of-lines-containing-the-string\/","og_locale":"en_US","og_type":"article","og_title":"Python: Search strings in a file and get line numbers of lines containing the string - Python Programs","og_description":"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. … Python: Search strings in a file and get line numbers of lines containing the string Read More »","og_url":"https:\/\/python-programs.com\/python-search-strings-in-a-file-and-get-line-numbers-of-lines-containing-the-string\/","og_site_name":"Python Programs","article_publisher":"https:\/\/www.facebook.com\/btechgeeks","article_published_time":"2023-10-26T10:23:08+00:00","article_modified_time":"2023-11-10T06:30:20+00:00","twitter_card":"summary_large_image","twitter_creator":"@btech_geeks","twitter_site":"@btech_geeks","twitter_misc":{"Written by":"Satyabrata Jena","Est. reading time":"5 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Organization","@id":"https:\/\/python-programs.com\/#organization","name":"BTech Geeks","url":"https:\/\/python-programs.com\/","sameAs":["https:\/\/www.instagram.com\/btechgeeks\/","https:\/\/www.linkedin.com\/in\/btechgeeks","https:\/\/in.pinterest.com\/btechgeek\/","https:\/\/www.youtube.com\/channel\/UC9MlCqdJ3lKqz2p5114SDIg","https:\/\/www.facebook.com\/btechgeeks","https:\/\/twitter.com\/btech_geeks"],"logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/python-programs.com\/#\/schema\/logo\/image\/","url":"https:\/\/python-programs.com\/wp-content\/uploads\/2020\/11\/BTechGeeks.png","contentUrl":"https:\/\/python-programs.com\/wp-content\/uploads\/2020\/11\/BTechGeeks.png","width":350,"height":70,"caption":"BTech Geeks"},"image":{"@id":"https:\/\/python-programs.com\/#\/schema\/logo\/image\/"}},{"@type":"WebSite","@id":"https:\/\/python-programs.com\/#website","url":"https:\/\/python-programs.com\/","name":"Python Programs","description":"Python Programs with Examples, How To Guides on Python","publisher":{"@id":"https:\/\/python-programs.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/python-programs.com\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/python-programs.com\/python-search-strings-in-a-file-and-get-line-numbers-of-lines-containing-the-string\/#webpage","url":"https:\/\/python-programs.com\/python-search-strings-in-a-file-and-get-line-numbers-of-lines-containing-the-string\/","name":"Python: Search strings in a file and get line numbers of lines containing the string - Python Programs","isPartOf":{"@id":"https:\/\/python-programs.com\/#website"},"datePublished":"2023-10-26T10:23:08+00:00","dateModified":"2023-11-10T06:30:20+00:00","breadcrumb":{"@id":"https:\/\/python-programs.com\/python-search-strings-in-a-file-and-get-line-numbers-of-lines-containing-the-string\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/python-programs.com\/python-search-strings-in-a-file-and-get-line-numbers-of-lines-containing-the-string\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/python-programs.com\/python-search-strings-in-a-file-and-get-line-numbers-of-lines-containing-the-string\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/python-programs.com\/"},{"@type":"ListItem","position":2,"name":"Python: Search strings in a file and get line numbers of lines containing the string"}]},{"@type":"Article","@id":"https:\/\/python-programs.com\/python-search-strings-in-a-file-and-get-line-numbers-of-lines-containing-the-string\/#article","isPartOf":{"@id":"https:\/\/python-programs.com\/python-search-strings-in-a-file-and-get-line-numbers-of-lines-containing-the-string\/#webpage"},"author":{"@id":"https:\/\/python-programs.com\/#\/schema\/person\/0f6d731bda7051ce3586f71299f391cd"},"headline":"Python: Search strings in a file and get line numbers of lines containing the string","datePublished":"2023-10-26T10:23:08+00:00","dateModified":"2023-11-10T06:30:20+00:00","mainEntityOfPage":{"@id":"https:\/\/python-programs.com\/python-search-strings-in-a-file-and-get-line-numbers-of-lines-containing-the-string\/#webpage"},"wordCount":381,"commentCount":0,"publisher":{"@id":"https:\/\/python-programs.com\/#organization"},"articleSection":["Python"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/python-programs.com\/python-search-strings-in-a-file-and-get-line-numbers-of-lines-containing-the-string\/#respond"]}]},{"@type":"Person","@id":"https:\/\/python-programs.com\/#\/schema\/person\/0f6d731bda7051ce3586f71299f391cd","name":"Satyabrata Jena","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/python-programs.com\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/c1bf8033ec357d085f41815bee1625cc?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/c1bf8033ec357d085f41815bee1625cc?s=96&d=mm&r=g","caption":"Satyabrata Jena"},"url":"https:\/\/python-programs.com\/author\/satyabrata\/"}]}},"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/posts\/5040"}],"collection":[{"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/users\/9"}],"replies":[{"embeddable":true,"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/comments?post=5040"}],"version-history":[{"count":3,"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/posts\/5040\/revisions"}],"predecessor-version":[{"id":5119,"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/posts\/5040\/revisions\/5119"}],"wp:attachment":[{"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/media?parent=5040"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/categories?post=5040"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/tags?post=5040"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}