{"id":12071,"date":"2020-10-28T02:52:06","date_gmt":"2020-10-28T09:52:06","guid":{"rendered":"https:\/\/careerkarma.com\/blog\/?p=12071"},"modified":"2023-12-01T04:03:27","modified_gmt":"2023-12-01T12:03:27","slug":"python-read-file","status":"publish","type":"post","link":"https:\/\/careerkarma.com\/blog\/python-read-file\/","title":{"rendered":"Python Read File: A Step-By-Step Guide"},"content":{"rendered":"\n<p><em>The open() function opens a file. You must use the &#8220;r&#8221; mode to read a file. The read(), readline(), readlines() functions return the contents of a file you have opened.<\/em><\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<p>Python is a useful programming language to use if you want to process data. The language has several built-in functions that make it easy to read, write, and manipulate data or files.<\/p>\n\n\n\n<p>Let\u2019s say that you have a list of employee names, and you want to check if a user\u2019s name is on that list. You could save the list of employee names as a file. Then, you could use Python to read that file and check if the employee\u2019s name is stored within that file.<\/p>\n\n\n\n<p>In this tutorial, we are going to explore the basics of reading files in Python. To start, we will discuss how to open and access a file. Then we will go on to explore how to read a file in Python.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Open File for Reading in Python<\/h2>\n\n\n\n<p>The first step to reading a file in Python is to open the file you want to read. You need to tell Python the name of the file you want to open.<\/p>\n\n\n\n<p>To read a file, you must first tell Python where that file resides. You can do so by specifying the path of the file and declaring it within a variable.<\/p>\n\n\n\n<p>Here\u2019s the syntax for opening a file in Python:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre>filename = &quot;\/users\/career_karma\/names.txt&quot;\nnames_file = open(filename, 'r')<\/pre><\/div>\n\n\n\n<p>Our code opens a file at the path we defined in the &#8220;filename&#8221; variable.<\/p>\n\n\n\n<p>The <em>r<\/em> flag at the end of the <em>open()<\/em> function tells Python that we only want to read our file. We could change this flag if we wanted to edit our file.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Python Read File<\/h2>\n\n\n\n<p>Now that our file is open, we can read it through Python. There are three functions that we can use to read data from a file, which are as follows:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><em>read()<\/em>: Returns the contents of a file<\/li><li><em>readline()<\/em>: Returns the next line of a file<\/li><li><em>readlines()<\/em>: Returns a list of lines in a file<\/li><\/ul>\n\n\n\n<p>Let\u2019s break down how each of these works. The <em>read()<\/em> method can return the entire contents of a file as a string.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Python Read Text File<\/h3>\n\n\n\n<p>Here\u2019s an example of <em>read()<\/em> operating on a text file that contains a list of names:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre>path = &quot;\/users\/career_karma\/names.txt&quot;\nnames_file = open(path, 'r')\nprint(names_file.read())<\/pre><\/div>\n\n\n\n<p>Our program returns the following:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre>&quot;Sally\\nAlex\/nPamela\/nJonas\/nLuke\/nWill\/n&quot;<\/pre><\/div>\n\n\n\n<p>The <em>read()<\/em> method returned everything within our <em>names<\/em> file, including the newline characters at the end of our string.<\/p>\n\n\n\n<p>The <em>readline()<\/em> function returns the next line of a file. readline() returns the text and the newline character at the end of the file. The following code will read the first line in our file:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre>print(names_file.readline())<\/pre><\/div>\n\n\n\n<p>Our code returns:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre>&quot;Sally\\n&quot;<\/pre><\/div>\n\n\n\n<p>If we wanted to read the first and second lines of our existing file, we would need to use the <em>readline()<\/em> function again:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre>names_file = open(path, 'r')\nprint(names_file.readline())\nprint(names_file.readline())<\/pre><\/div>\n\n\n\n<p>Our code returns the following output:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre>&quot;Sally\\n&quot;\n&quot;Alex\\n&quot;<\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\">Python Read File Line-by-Line<\/h3>\n\n\n\n<p>The <em>readline()<\/em> function can be useful if you want to read a file line by line. The function is commonly used within a <em>for<\/em> loop to read multiple lines in a file, like this:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre>for i in range(0, 2):\n\tprint(names_file.readline())<\/pre><\/div>\n\n\n\n<p>Our code returns the following:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre>&quot;Sally\\n&quot;\n&quot;Alex\\n&quot;<\/pre><\/div>\n\n\n\n<p>Finally, the <em>readlines()<\/em> method returns a list of the lines in a file. This function returns an array, and each item represents a single line within a file:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre>print(names_file.readlines())<\/pre><\/div>\n\n\n\n<p>The program returns the following:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre>['Sally\\n', 'Alex\\n', 'Pamela\\n', 'Jonas\\n', 'Luke\\n', 'Will']<\/pre><\/div>\n\n\n\n<p>Once you have read a file, you can\u2019t reread it. So, when you have read the file using <em>readlines()<\/em>, trying to reread the file using any read file operation will return an empty string. If you want to read a file multiple times, you\u2019ll need to open the file again and read it.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>You can use the <em>read()<\/em>, <em>readline()<\/em>, and <em>readlines()<\/em> functions to read certain parts of a file. Then, you manipulate the data depending on your needs. Today, we covered how to open a file, read it using specific methods, and how to close it in Python.<\/p>\n\n\n\n<p>Now you\u2019re ready to open and read Python files like an expert! To learn more about Python, read our guide on <a href=\"https:\/\/careerkarma.com\/blog\/how-to-learn-python\/\">How to Code in Python<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"The open() function opens a file. You must use the \"r\" mode to read a file. The read(), readline(), readlines() functions return the contents of a file you have opened. Python is a useful programming language to use if you want to process data. The language has several built-in functions that make it easy to&hellip;","protected":false},"author":240,"featured_media":12072,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[16578],"tags":[12687],"class_list":{"0":"post-12071","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-python","8":"tag-tutorial"},"acf":{"post_sub_title":"","sprint_id":"","query_class":"Python","school_sft":"","parent_sft":"","school_privacy_policy":"","has_review":null,"is_sponser_post":"","is_guest_post":""},"yoast_head":"<!-- This site is optimized with the Yoast SEO Premium plugin v27.0 (Yoast SEO v27.0) - https:\/\/yoast.com\/product\/yoast-seo-premium-wordpress\/ -->\n<title>Python Read File: A Step-By-Step Guide | Career Karma<\/title>\n<meta name=\"description\" content=\"Reading files allows coders to get data from another source in their programs. Learn about how to open, read, and close files in Python.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/careerkarma.com\/blog\/python-read-file\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Python Read File: A Step-By-Step Guide\" \/>\n<meta property=\"og:description\" content=\"Reading files allows coders to get data from another source in their programs. Learn about how to open, read, and close files in Python.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/careerkarma.com\/blog\/python-read-file\/\" \/>\n<meta property=\"og:site_name\" content=\"Career Karma\" \/>\n<meta property=\"article:publisher\" content=\"http:\/\/facebook.com\/careerkarmaapp\" \/>\n<meta property=\"article:published_time\" content=\"2020-10-28T09:52:06+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-12-01T12:03:27+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/careerkarma.com\/blog\/wp-content\/uploads\/2020\/02\/PYTHON-READ-FILE.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1000\" \/>\n\t<meta property=\"og:image:height\" content=\"668\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"James Gallagher\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@career_karma\" \/>\n<meta name=\"twitter:site\" content=\"@career_karma\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"James Gallagher\" \/>\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\":\"Article\",\"@id\":\"https:\/\/careerkarma.com\/blog\/python-read-file\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/careerkarma.com\/blog\/python-read-file\/\"},\"author\":{\"name\":\"James Gallagher\",\"@id\":\"https:\/\/careerkarma.com\/blog\/#\/schema\/person\/e79364792443fbff794a144c67ec8e94\"},\"headline\":\"Python Read File: A Step-By-Step Guide\",\"datePublished\":\"2020-10-28T09:52:06+00:00\",\"dateModified\":\"2023-12-01T12:03:27+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/careerkarma.com\/blog\/python-read-file\/\"},\"wordCount\":686,\"commentCount\":0,\"image\":{\"@id\":\"https:\/\/careerkarma.com\/blog\/python-read-file\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/careerkarma.com\/blog\/wp-content\/uploads\/2020\/02\/PYTHON-READ-FILE.jpg\",\"keywords\":[\"tutorial\"],\"articleSection\":[\"Python\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/careerkarma.com\/blog\/python-read-file\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/careerkarma.com\/blog\/python-read-file\/\",\"url\":\"https:\/\/careerkarma.com\/blog\/python-read-file\/\",\"name\":\"Python Read File: A Step-By-Step Guide | Career Karma\",\"isPartOf\":{\"@id\":\"https:\/\/careerkarma.com\/blog\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/careerkarma.com\/blog\/python-read-file\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/careerkarma.com\/blog\/python-read-file\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/careerkarma.com\/blog\/wp-content\/uploads\/2020\/02\/PYTHON-READ-FILE.jpg\",\"datePublished\":\"2020-10-28T09:52:06+00:00\",\"dateModified\":\"2023-12-01T12:03:27+00:00\",\"author\":{\"@id\":\"https:\/\/careerkarma.com\/blog\/#\/schema\/person\/e79364792443fbff794a144c67ec8e94\"},\"description\":\"Reading files allows coders to get data from another source in their programs. Learn about how to open, read, and close files in Python.\",\"breadcrumb\":{\"@id\":\"https:\/\/careerkarma.com\/blog\/python-read-file\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/careerkarma.com\/blog\/python-read-file\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/careerkarma.com\/blog\/python-read-file\/#primaryimage\",\"url\":\"https:\/\/careerkarma.com\/blog\/wp-content\/uploads\/2020\/02\/PYTHON-READ-FILE.jpg\",\"contentUrl\":\"https:\/\/careerkarma.com\/blog\/wp-content\/uploads\/2020\/02\/PYTHON-READ-FILE.jpg\",\"width\":1000,\"height\":668},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/careerkarma.com\/blog\/python-read-file\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Blog\",\"item\":\"https:\/\/careerkarma.com\/blog\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Python\",\"item\":\"https:\/\/careerkarma.com\/blog\/python\/\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"Python Read File: A Step-By-Step Guide\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/careerkarma.com\/blog\/#website\",\"url\":\"https:\/\/careerkarma.com\/blog\/\",\"name\":\"Career Karma\",\"description\":\"Latest Coding Bootcamp News &amp; Career Hacks from Industry Insiders\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/careerkarma.com\/blog\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"https:\/\/careerkarma.com\/blog\/#\/schema\/person\/e79364792443fbff794a144c67ec8e94\",\"name\":\"James Gallagher\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/careerkarma.com\/blog\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/careerkarma.com\/blog\/wp-content\/uploads\/2020\/01\/james-gallagher-150x150.jpg\",\"contentUrl\":\"https:\/\/careerkarma.com\/blog\/wp-content\/uploads\/2020\/01\/james-gallagher-150x150.jpg\",\"caption\":\"James Gallagher\"},\"description\":\"James Gallagher is a self-taught programmer and the technical content manager at Career Karma. He has experience in range of programming languages and extensive expertise in Python, HTML, CSS, and JavaScript. James has written hundreds of programming tutorials, and he frequently contributes to publications like Codecademy, Treehouse, Repl.it, Afrotech, and others.\",\"url\":\"https:\/\/careerkarma.com\/blog\/author\/jamesgallagher\/\"}]}<\/script>\n<!-- \/ Yoast SEO Premium plugin. -->","yoast_head_json":{"title":"Python Read File: A Step-By-Step Guide | Career Karma","description":"Reading files allows coders to get data from another source in their programs. Learn about how to open, read, and close files in Python.","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:\/\/careerkarma.com\/blog\/python-read-file\/","og_locale":"en_US","og_type":"article","og_title":"Python Read File: A Step-By-Step Guide","og_description":"Reading files allows coders to get data from another source in their programs. Learn about how to open, read, and close files in Python.","og_url":"https:\/\/careerkarma.com\/blog\/python-read-file\/","og_site_name":"Career Karma","article_publisher":"http:\/\/facebook.com\/careerkarmaapp","article_published_time":"2020-10-28T09:52:06+00:00","article_modified_time":"2023-12-01T12:03:27+00:00","og_image":[{"width":1000,"height":668,"url":"https:\/\/careerkarma.com\/blog\/wp-content\/uploads\/2020\/02\/PYTHON-READ-FILE.jpg","type":"image\/jpeg"}],"author":"James Gallagher","twitter_card":"summary_large_image","twitter_creator":"@career_karma","twitter_site":"@career_karma","twitter_misc":{"Written by":"James Gallagher","Est. reading time":"4 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/careerkarma.com\/blog\/python-read-file\/#article","isPartOf":{"@id":"https:\/\/careerkarma.com\/blog\/python-read-file\/"},"author":{"name":"James Gallagher","@id":"https:\/\/careerkarma.com\/blog\/#\/schema\/person\/e79364792443fbff794a144c67ec8e94"},"headline":"Python Read File: A Step-By-Step Guide","datePublished":"2020-10-28T09:52:06+00:00","dateModified":"2023-12-01T12:03:27+00:00","mainEntityOfPage":{"@id":"https:\/\/careerkarma.com\/blog\/python-read-file\/"},"wordCount":686,"commentCount":0,"image":{"@id":"https:\/\/careerkarma.com\/blog\/python-read-file\/#primaryimage"},"thumbnailUrl":"https:\/\/careerkarma.com\/blog\/wp-content\/uploads\/2020\/02\/PYTHON-READ-FILE.jpg","keywords":["tutorial"],"articleSection":["Python"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/careerkarma.com\/blog\/python-read-file\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/careerkarma.com\/blog\/python-read-file\/","url":"https:\/\/careerkarma.com\/blog\/python-read-file\/","name":"Python Read File: A Step-By-Step Guide | Career Karma","isPartOf":{"@id":"https:\/\/careerkarma.com\/blog\/#website"},"primaryImageOfPage":{"@id":"https:\/\/careerkarma.com\/blog\/python-read-file\/#primaryimage"},"image":{"@id":"https:\/\/careerkarma.com\/blog\/python-read-file\/#primaryimage"},"thumbnailUrl":"https:\/\/careerkarma.com\/blog\/wp-content\/uploads\/2020\/02\/PYTHON-READ-FILE.jpg","datePublished":"2020-10-28T09:52:06+00:00","dateModified":"2023-12-01T12:03:27+00:00","author":{"@id":"https:\/\/careerkarma.com\/blog\/#\/schema\/person\/e79364792443fbff794a144c67ec8e94"},"description":"Reading files allows coders to get data from another source in their programs. Learn about how to open, read, and close files in Python.","breadcrumb":{"@id":"https:\/\/careerkarma.com\/blog\/python-read-file\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/careerkarma.com\/blog\/python-read-file\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/careerkarma.com\/blog\/python-read-file\/#primaryimage","url":"https:\/\/careerkarma.com\/blog\/wp-content\/uploads\/2020\/02\/PYTHON-READ-FILE.jpg","contentUrl":"https:\/\/careerkarma.com\/blog\/wp-content\/uploads\/2020\/02\/PYTHON-READ-FILE.jpg","width":1000,"height":668},{"@type":"BreadcrumbList","@id":"https:\/\/careerkarma.com\/blog\/python-read-file\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Blog","item":"https:\/\/careerkarma.com\/blog\/"},{"@type":"ListItem","position":2,"name":"Python","item":"https:\/\/careerkarma.com\/blog\/python\/"},{"@type":"ListItem","position":3,"name":"Python Read File: A Step-By-Step Guide"}]},{"@type":"WebSite","@id":"https:\/\/careerkarma.com\/blog\/#website","url":"https:\/\/careerkarma.com\/blog\/","name":"Career Karma","description":"Latest Coding Bootcamp News &amp; Career Hacks from Industry Insiders","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/careerkarma.com\/blog\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/careerkarma.com\/blog\/#\/schema\/person\/e79364792443fbff794a144c67ec8e94","name":"James Gallagher","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/careerkarma.com\/blog\/#\/schema\/person\/image\/","url":"https:\/\/careerkarma.com\/blog\/wp-content\/uploads\/2020\/01\/james-gallagher-150x150.jpg","contentUrl":"https:\/\/careerkarma.com\/blog\/wp-content\/uploads\/2020\/01\/james-gallagher-150x150.jpg","caption":"James Gallagher"},"description":"James Gallagher is a self-taught programmer and the technical content manager at Career Karma. He has experience in range of programming languages and extensive expertise in Python, HTML, CSS, and JavaScript. James has written hundreds of programming tutorials, and he frequently contributes to publications like Codecademy, Treehouse, Repl.it, Afrotech, and others.","url":"https:\/\/careerkarma.com\/blog\/author\/jamesgallagher\/"}]}},"_links":{"self":[{"href":"https:\/\/careerkarma.com\/blog\/wp-json\/wp\/v2\/posts\/12071","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/careerkarma.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/careerkarma.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/careerkarma.com\/blog\/wp-json\/wp\/v2\/users\/240"}],"replies":[{"embeddable":true,"href":"https:\/\/careerkarma.com\/blog\/wp-json\/wp\/v2\/comments?post=12071"}],"version-history":[{"count":0,"href":"https:\/\/careerkarma.com\/blog\/wp-json\/wp\/v2\/posts\/12071\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/careerkarma.com\/blog\/wp-json\/wp\/v2\/media\/12072"}],"wp:attachment":[{"href":"https:\/\/careerkarma.com\/blog\/wp-json\/wp\/v2\/media?parent=12071"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/careerkarma.com\/blog\/wp-json\/wp\/v2\/categories?post=12071"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/careerkarma.com\/blog\/wp-json\/wp\/v2\/tags?post=12071"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}