{"id":3530,"date":"2021-04-24T11:15:56","date_gmt":"2021-04-24T05:45:56","guid":{"rendered":"https:\/\/python-programs.com\/?p=3530"},"modified":"2021-11-22T18:44:53","modified_gmt":"2021-11-22T13:14:53","slug":"5-different-ways-to-read-a-file-line-by-line-in-python","status":"publish","type":"post","link":"https:\/\/python-programs.com\/5-different-ways-to-read-a-file-line-by-line-in-python\/","title":{"rendered":"5 Different ways to read a file line by line in Python"},"content":{"rendered":"

Python gives us functions for writing ,creating and reading files.Ok llike we have some file in our directory so in python we can read that file and also make some modification on it. Normal text files and binary files there are two types of files that can be handled in python.There are different ways to read a file line by line in Python.<\/p>\n

We have one\u00a0 file intro1.txt in our directory and we want to read it line by line.Lets see how will we do that.<\/p>\n

Using readlines()<\/h3>\n

readlines() we can use for small file. It reads all files details from memory, then\u00a0 separate into lines and returns all in a list.\u00a0 All the List returned by readlines or readline will store the newline character at the end.<\/p>\n

Lets take an example,<\/p>\n

fileHandler = open ('c:\\\\new folder\\intro1.txt', \"r\")\r\n# Get list of all lines in file\r\nlistOfLines = fileHandler.readlines()\r\nfor line in listOfLines:\r\n    print(line.strip()) \r\nfileHandler.close()<\/pre>\n

Output:<\/strong><\/p>\n

RESTART: C:\/Users\/HP\/Desktop\/filehandling.py\r\nPython is an interpreted, object-oriented, high-level programming language with dynamic semantics.\r\nPython's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance.\r\nPython supports modules and packages, which encourages program modularity and code reuse.\r\n<\/pre>\n

So in above example we have seen that listOfLines = fileHandler.readlines()<\/code>\u00a0this will return a list of lines in file. We can iterate over that list and strip() the new line character then print the line .<\/p>\n

Above case is only use for small file for large file we have to look up some other methods because it use lots of memory.<\/p>\n

Using readline()<\/h3>\n

For working with large file we have readline().It will read file line by line instead of storing all at one time.Also, if the end of the file is reached, it will return an empty string.<\/p>\n

fileHandler = open (\"c:\\\\new folder\\intro1.txt\", \"r\")\r\nwhile True:\r\n    \r\n    line = fileHandler.readline()\r\n    # If line is empty then end of file reached\r\n    if not line :\r\n        break;\r\n    print(line.strip())\r\n   \r\nfileHandler.close()<\/pre>\n

Output:<\/strong><\/p>\n

RESTART: C:\/Users\/HP\/Desktop\/filehandling.py\r\n\r\nPython is an interpreted, object-oriented, high-level programming language with dynamic semantics. \r\nPython's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance.\r\n Python supports modules and packages, which encourages program modularity and code reuse.\r\n\r\n<\/pre>\n

Using context manager (with block)<\/h3>\n

If we open any file it is very important to close that file,if we did not close then it will automatically close but sometime when there is\u00a0 large function which not going to end soon.In that case we take help of context manager to cleanup and closeup.<\/p>\n

fileHandler = open(\"c:\\\\new folder\\intro1.txt\", \"r\")\r\nline = fileHandler.readline()\r\nfor line in fileHandler:\r\n    print(\"Line{}: {}\".format(count, line.strip()))\r\n   \r\nfileHandler.close()<\/pre>\n

Output:<\/strong><\/p>\n

RESTART: C:\/Users\/HP\/Desktop\/filehandling.py \r\nPython is an interpreted, object-oriented, high-level programming language with dynamic semantics.\r\nPython's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance.\r\nPython supports modules and packages, which encourages program modularity and code reuse.\r\n<\/pre>\n

After termination of loop file will automatically close,even if there is any exception it will also terminates.<\/p>\n

\u00a0Using context manager (with block)get List of lines in file<\/h3>\n
listOfLines = list()        \r\nwith open(\"c:\\\\new folder\\intro1.txt\", \"r\") as file:\r\n    for line in file:\r\n        listOfLines.append(line.strip()) \r\n    print(listOfLines)\r\n<\/pre>\n

Output:<\/strong><\/p>\n

['Python is an interpreted, object-oriented, high-level programming language with dynamic semantics.', \r\n\"Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance.\", \r\n'Python supports modules and packages, which encourages program modularity and code reuse.']\r\n\r\n<\/pre>\n

So in above example we have iterate all the lines in file and create a list.<\/p>\n

Using context manager and while loop read contents of file line by line<\/h3>\n

So in this method we are going to use while loop and context manager for reading of any file.So in while loop we can give any condition according to this it iterate over lines in file.<\/p>\n

with open(\"c:\\\\new folder\\intro1.txt\", \"r\") as fileHandler:  \r\n    # Read next line\r\n    line = fileHandler.readline()\r\n    # check line is not empty\r\n    while line:\r\n        print(line.strip())\r\n        line = fileHandler.readline()<\/pre>\n

Output:<\/strong><\/p>\n

RESTART: C:\/Users\/HP\/Desktop\/filehandling.py\r\n Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. \r\nPython's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance. \r\nPython supports modules and packages, which encourages program modularity and code reuse.\r\n\r\n<\/pre>\n

Conclusion:<\/h3>\n

So in this article we have shown you different methods to read any file.Hope you enjoyed the session.<\/p>\n","protected":false},"excerpt":{"rendered":"

Python gives us functions for writing ,creating and reading files.Ok llike we have some file in our directory so in python we can read that file and also make some modification on it. Normal text files and binary files there are two types of files that can be handled in python.There are different ways to …<\/p>\n

5 Different ways to read a file line by line in Python<\/span> Read More »<\/a><\/p>\n","protected":false},"author":4,"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":"\n5 Different ways to read a file line by line in Python - 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\/5-different-ways-to-read-a-file-line-by-line-in-python\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"5 Different ways to read a file line by line in Python - Python Programs\" \/>\n<meta property=\"og:description\" content=\"Python gives us functions for writing ,creating and reading files.Ok llike we have some file in our directory so in python we can read that file and also make some modification on it. Normal text files and binary files there are two types of files that can be handled in python.There are different ways to … 5 Different ways to read a file line by line in Python Read More »\" \/>\n<meta property=\"og:url\" content=\"https:\/\/python-programs.com\/5-different-ways-to-read-a-file-line-by-line-in-python\/\" \/>\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=\"2021-04-24T05:45:56+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2021-11-22T13:14:53+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=\"Shikha Mishra\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"4 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\/5-different-ways-to-read-a-file-line-by-line-in-python\/#webpage\",\"url\":\"https:\/\/python-programs.com\/5-different-ways-to-read-a-file-line-by-line-in-python\/\",\"name\":\"5 Different ways to read a file line by line in Python - Python Programs\",\"isPartOf\":{\"@id\":\"https:\/\/python-programs.com\/#website\"},\"datePublished\":\"2021-04-24T05:45:56+00:00\",\"dateModified\":\"2021-11-22T13:14:53+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/python-programs.com\/5-different-ways-to-read-a-file-line-by-line-in-python\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/python-programs.com\/5-different-ways-to-read-a-file-line-by-line-in-python\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/python-programs.com\/5-different-ways-to-read-a-file-line-by-line-in-python\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/python-programs.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"5 Different ways to read a file line by line in Python\"}]},{\"@type\":\"Article\",\"@id\":\"https:\/\/python-programs.com\/5-different-ways-to-read-a-file-line-by-line-in-python\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/python-programs.com\/5-different-ways-to-read-a-file-line-by-line-in-python\/#webpage\"},\"author\":{\"@id\":\"https:\/\/python-programs.com\/#\/schema\/person\/7a690ac49394cc96d2e839bf9a746594\"},\"headline\":\"5 Different ways to read a file line by line in Python\",\"datePublished\":\"2021-04-24T05:45:56+00:00\",\"dateModified\":\"2021-11-22T13:14:53+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/python-programs.com\/5-different-ways-to-read-a-file-line-by-line-in-python\/#webpage\"},\"wordCount\":418,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/python-programs.com\/#organization\"},\"articleSection\":[\"Python\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/python-programs.com\/5-different-ways-to-read-a-file-line-by-line-in-python\/#respond\"]}]},{\"@type\":\"Person\",\"@id\":\"https:\/\/python-programs.com\/#\/schema\/person\/7a690ac49394cc96d2e839bf9a746594\",\"name\":\"Shikha Mishra\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/python-programs.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/10a27cfafdf21564c686b80411336ece?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/10a27cfafdf21564c686b80411336ece?s=96&d=mm&r=g\",\"caption\":\"Shikha Mishra\"},\"url\":\"https:\/\/python-programs.com\/author\/shikha\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"5 Different ways to read a file line by line in Python - 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\/5-different-ways-to-read-a-file-line-by-line-in-python\/","og_locale":"en_US","og_type":"article","og_title":"5 Different ways to read a file line by line in Python - Python Programs","og_description":"Python gives us functions for writing ,creating and reading files.Ok llike we have some file in our directory so in python we can read that file and also make some modification on it. Normal text files and binary files there are two types of files that can be handled in python.There are different ways to … 5 Different ways to read a file line by line in Python Read More »","og_url":"https:\/\/python-programs.com\/5-different-ways-to-read-a-file-line-by-line-in-python\/","og_site_name":"Python Programs","article_publisher":"https:\/\/www.facebook.com\/btechgeeks","article_published_time":"2021-04-24T05:45:56+00:00","article_modified_time":"2021-11-22T13:14:53+00:00","twitter_card":"summary_large_image","twitter_creator":"@btech_geeks","twitter_site":"@btech_geeks","twitter_misc":{"Written by":"Shikha Mishra","Est. reading time":"4 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\/5-different-ways-to-read-a-file-line-by-line-in-python\/#webpage","url":"https:\/\/python-programs.com\/5-different-ways-to-read-a-file-line-by-line-in-python\/","name":"5 Different ways to read a file line by line in Python - Python Programs","isPartOf":{"@id":"https:\/\/python-programs.com\/#website"},"datePublished":"2021-04-24T05:45:56+00:00","dateModified":"2021-11-22T13:14:53+00:00","breadcrumb":{"@id":"https:\/\/python-programs.com\/5-different-ways-to-read-a-file-line-by-line-in-python\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/python-programs.com\/5-different-ways-to-read-a-file-line-by-line-in-python\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/python-programs.com\/5-different-ways-to-read-a-file-line-by-line-in-python\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/python-programs.com\/"},{"@type":"ListItem","position":2,"name":"5 Different ways to read a file line by line in Python"}]},{"@type":"Article","@id":"https:\/\/python-programs.com\/5-different-ways-to-read-a-file-line-by-line-in-python\/#article","isPartOf":{"@id":"https:\/\/python-programs.com\/5-different-ways-to-read-a-file-line-by-line-in-python\/#webpage"},"author":{"@id":"https:\/\/python-programs.com\/#\/schema\/person\/7a690ac49394cc96d2e839bf9a746594"},"headline":"5 Different ways to read a file line by line in Python","datePublished":"2021-04-24T05:45:56+00:00","dateModified":"2021-11-22T13:14:53+00:00","mainEntityOfPage":{"@id":"https:\/\/python-programs.com\/5-different-ways-to-read-a-file-line-by-line-in-python\/#webpage"},"wordCount":418,"commentCount":0,"publisher":{"@id":"https:\/\/python-programs.com\/#organization"},"articleSection":["Python"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/python-programs.com\/5-different-ways-to-read-a-file-line-by-line-in-python\/#respond"]}]},{"@type":"Person","@id":"https:\/\/python-programs.com\/#\/schema\/person\/7a690ac49394cc96d2e839bf9a746594","name":"Shikha Mishra","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/python-programs.com\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/10a27cfafdf21564c686b80411336ece?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/10a27cfafdf21564c686b80411336ece?s=96&d=mm&r=g","caption":"Shikha Mishra"},"url":"https:\/\/python-programs.com\/author\/shikha\/"}]}},"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/posts\/3530"}],"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\/4"}],"replies":[{"embeddable":true,"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/comments?post=3530"}],"version-history":[{"count":2,"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/posts\/3530\/revisions"}],"predecessor-version":[{"id":3576,"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/posts\/3530\/revisions\/3576"}],"wp:attachment":[{"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/media?parent=3530"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/categories?post=3530"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/tags?post=3530"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}