{"id":9549,"date":"2021-06-13T17:32:18","date_gmt":"2021-06-13T12:02:18","guid":{"rendered":"https:\/\/pynative.com\/?p=9549"},"modified":"2021-07-25T11:28:42","modified_gmt":"2021-07-25T05:58:42","slug":"python-file-open","status":"publish","type":"post","link":"https:\/\/pynative.com\/python-file-open\/","title":{"rendered":"Open a File in Python"},"content":{"rendered":"\n<p>In this tutorial, you&#8217;ll learn how to open a file in Python. <\/p>\n\n\n\n<p>The data can be in the form of files such as text, csv, and binary files. To extract data from these files, Python comes with built-in functions to open a file and then read and write the file&#8217;s contents.<\/p>\n\n\n\n<p><strong>After reading this tutorial, you can learn<\/strong>: &#8211;<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>How to open a file in Python using both relative and absolute path<\/li><li>Different file access modes for opening a file<\/li><li>How to open a file for reading, writing, and appending.<\/li><li>How to open a file using the <code>with<\/code> statement<\/li><li>Importance of closing a file<\/li><\/ul>\n\n\n\n<div class=\"wp-block-yoast-seo-table-of-contents yoast-table-of-contents\"><h2>Table of contents<\/h2><ul><li><a href=\"#h-access-modes-for-opening-a-file\" data-level=\"2\">Access Modes for Opening a file<\/a><\/li><li><a href=\"#h-steps-for-opening-file-in-python\" data-level=\"2\">Steps For Opening File in Python<\/a><ul><li><a href=\"#h-example-opening-a-file-in-read-mode\" data-level=\"3\">Example: Opening a File in read mode<\/a><\/li><li><a href=\"#h-opening-a-file-with-relative-path\" data-level=\"3\">Opening a File with Relative Path<\/a><\/li><li><a href=\"#h-handling-the-filenotfounderror\" data-level=\"3\">Handling the FileNotFoundError<\/a><\/li><\/ul><\/li><li><a href=\"#h-file-open-function\" data-level=\"2\">File open() function <\/a><\/li><li><a href=\"#h-opening-a-file-in-read-mode\" data-level=\"2\">Opening a File in Read mode<\/a><\/li><li><a href=\"#h-opening-a-file-in-write-mode\" data-level=\"2\">Opening a File in Write Mode<\/a><\/li><li><a href=\"#h-opening-a-file-in-append-mode\" data-level=\"2\">Opening a File in Append Mode<\/a><\/li><li><a href=\"#h-closing-a-file\" data-level=\"2\">Closing a File <\/a><\/li><li><a href=\"#h-opening-file-using-with-statement\" data-level=\"2\">Opening file using with statement<\/a><\/li><li><a href=\"#h-creating-a-new-file\" data-level=\"2\">Creating a new file<\/a><\/li><li><a href=\"#h-opening-a-file-for-multiple-operations\" data-level=\"2\">Opening a File for multiple operations<\/a><\/li><li><a href=\"#h-opening-a-binary-file\" data-level=\"2\">Opening a Binary file<\/a><\/li><li><a href=\"#h-summary\" data-level=\"2\">Summary<\/a><\/li><\/ul><\/div>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-access-modes-for-opening-a-file\">Access Modes for Opening a file<\/h2>\n\n\n\n<p>The access mode parameter in the <code>open()<\/code> function primarily mentions <strong>the purpose of opening the file<\/strong> or the type of operation we are planning to do with the file after opening. in Python, the following are the different characters that we use for mentioning the file opening modes.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>File Mode<\/th><th>Meaning<\/th><\/tr><\/thead><tbody><tr><td><code>r<\/code><\/td><td>Opens a file for reading (default)<\/td><\/tr><tr><td><code>w<\/code><\/td><td>Open a file for writing. If a file already exists, it deletes all the existing contents and adds new content from the start of the file.<\/td><\/tr><tr><td><code>x<\/code><\/td><td>Open a file for exclusive creation. If the file already exists, this operation fails.<\/td><\/tr><tr><td><code>a<\/code><\/td><td>Open a file in the append mode and add new content at the end of the file.<\/td><\/tr><tr><td><code>b<\/code><\/td><td>Open the file in binary mode.<\/td><\/tr><tr><td><code>t<\/code><\/td><td>Opens a file in a text mode (default).<\/td><\/tr><tr><td><code>+<\/code><\/td><td>Open a file for updating (reading and writing).<\/td><\/tr><\/tbody><\/table><figcaption>File access mode<\/figcaption><\/figure>\n\n\n\n<h2 class=\"stepsh wp-block-heading\" id=\"h-steps-for-opening-file-in-python\">Steps For Opening File in Python<\/h2>\n\n\n\n<div class=\"wp-block-columns steps is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex\">\n<div class=\"wp-block-column is-layout-flow wp-block-column-is-layout-flow\">\n<div class=\"schema-how-to wp-block-yoast-how-to-block\"><p class=\"schema-how-to-description\">To open a file in Python, Please follow these steps:<\/p> <ol class=\"schema-how-to-steps\"><li class=\"schema-how-to-step\" id=\"how-to-step-1623071602523\"><strong class=\"schema-how-to-step-name\">Find the path of a file<\/strong> <p class=\"schema-how-to-step-text\">We can open a file using both relative path and absolute path. The path is the location of the file on the disk.<br\/>An <strong>absolute path<\/strong> contains the complete directory list required to locate the file.<br\/>A <strong>relative path<\/strong> contains the current directory and then the file name.<\/p> <\/li><li class=\"schema-how-to-step\" id=\"how-to-step-1623072196137\"><strong class=\"schema-how-to-step-name\">Decide the access mode<\/strong> <p class=\"schema-how-to-step-text\">The access mode specifies the operation you wanted to perform on the file, such as reading or writing. To open and read a file, use the <code>r<\/code> access mode. To open a file for writing, use the <code>w<\/code> mode.<\/p> <\/li><li class=\"schema-how-to-step\" id=\"how-to-step-1623072223707\"><strong class=\"schema-how-to-step-name\">Pass file path and access mode to the open() function<\/strong> <p class=\"schema-how-to-step-text\"><code>fp= open(r\"File_Name\", \"Access_Mode\")<\/code>.  For example, to <strong>open and read<\/strong>: <code>fp = open('sample.txt', 'r')<\/code><br\/><\/p> <\/li><li class=\"schema-how-to-step\" id=\"how-to-step-1623072253286\"><strong class=\"schema-how-to-step-name\">Read content from a file.<\/strong> <p class=\"schema-how-to-step-text\">Next, <a href=\"https:\/\/pynative.com\/python-read-file\/\">read a file<\/a> using the <code>read()<\/code> method. For example, <code>content = fp.read()<\/code>. You can also use <code>readline()<\/code>, and <code>readlines()<\/code><\/p> <\/li><li class=\"schema-how-to-step\" id=\"how-to-step-1623072256024\"><strong class=\"schema-how-to-step-name\">Write content into the file<\/strong> <p class=\"schema-how-to-step-text\">If you have opened a file in a write mode, you can <a href=\"https:\/\/pynative.com\/python-write-file\/\">write or append text to the file<\/a> using the <code>write()<\/code> method. For example, <code>fp.write('content')<\/code>. You can also use the <code>writeine()<\/code> method.<\/p> <\/li><li class=\"schema-how-to-step\" id=\"how-to-step-1623073790009\"><strong class=\"schema-how-to-step-name\">Close file after completing operation<\/strong> <p class=\"schema-how-to-step-text\">We need to make sure that the file will be closed properly after completing the file operation. Use <code>fp.close()<\/code> to close a file.<\/p> <\/li><\/ol><\/div>\n<\/div>\n<\/div>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-example-opening-a-file-in-read-mode\"><strong>Example: Opening a File in read mode<\/strong><\/h3>\n\n\n\n<p>The following code shows <strong>how to open a text file for reading<\/strong> in Python. In this example, we are <strong>opening a file using the absolute Path<\/strong>.<\/p>\n\n\n\n<p>An absolute path contains the entire path to the file or directory that we need to access. It includes the complete directory list required to locate the file.<\/p>\n\n\n\n<div class=\"wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex\">\n<div class=\"wp-block-column is-layout-flow wp-block-column-is-layout-flow\">\n<p>For example, <code>\/home\/reports\/samples.txt<\/code> is an absolute path to discover the samples.txt. All of the information needed to find the file is contained in the path string.<\/p>\n\n\n\n<p>See the attached file used in the example and an image to show the file&#8217;s content for reference.<\/p>\n<\/div>\n\n\n\n<div class=\"wp-block-column is-layout-flow wp-block-column-is-layout-flow\">\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"391\" height=\"317\" src=\"https:\/\/pynative.com\/wp-content\/uploads\/2021\/06\/sample_text_file.png\" alt=\"sample text file\" class=\"wp-image-9573\" srcset=\"https:\/\/pynative.com\/wp-content\/uploads\/2021\/06\/sample_text_file.png 391w, https:\/\/pynative.com\/wp-content\/uploads\/2021\/06\/sample_text_file-300x243.png 300w\" sizes=\"auto, (max-width: 391px) 100vw, 391px\" \/><figcaption>sample text file<\/figcaption><\/figure><\/div>\n<\/div>\n<\/div>\n\n\n<div class=\"hljstoolbar\"><pre id=\"code1\"  id=\"norun\" class=\"wp-block-code language-python\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-comment\"># Opening the file with absolute path<\/span>\nfp = open(<span class=\"hljs-string\">r'E:\\demos\\files\\sample.txt'<\/span>, <span class=\"hljs-string\">'r'<\/span>)\n<span class=\"hljs-comment\"># read file<\/span>\nprint(fp.read())\n<span class=\"hljs-comment\"># Closing the file after reading<\/span>\nfp.close()\n\n<span class=\"hljs-comment\"># path if you using MacOs<\/span>\n<span class=\"hljs-comment\"># fp = open(r\"\/Users\/myfiles\/sample.txt\", \"r\")<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre><button class=\"hljs-copy-button\" onclick=\"copy_code('code1', this);\"><i class=\"far fa-copy1\" aria-hidden=\"true\"><\/i><\/button><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">Welcome to PYnative.com\nThis is a sample.txt<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-opening-a-file-with-relative-path\">Opening a File with Relative Path<\/h3>\n\n\n\n<p>A relative path is a path that starts with the working directory or the current directory and then will start looking for the file from that directory to the file name.<\/p>\n\n\n\n<p>For example, <code>reports\/sample.txt<\/code> is a relative path. In the relative path, it will look for a file into the directory where this script is running.<\/p>\n\n\n<div class=\"hljstoolbar\"><pre id=\"code2\"  id=\"norun\" class=\"wp-block-code language-python\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-comment\"># Opening the file with relative path<\/span>\n<span class=\"hljs-keyword\">try<\/span>:\n    fp = open(<span class=\"hljs-string\">\"sample.txt\"<\/span>, <span class=\"hljs-string\">\"r\"<\/span>)\n    print(fp.read())\n    fp.close()\n<span class=\"hljs-keyword\">except<\/span> FileNotFoundError:\n    print(<span class=\"hljs-string\">\"Please check the path.\"<\/span>)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre><button class=\"hljs-copy-button\" onclick=\"copy_code('code2', this);\"><i class=\"far fa-copy1\" aria-hidden=\"true\"><\/i><\/button><\/div>\n\n\n<h3 class=\"wp-block-heading\" id=\"h-handling-the-filenotfounderror\">Handling the <code>FileNotFoundError<\/code><\/h3>\n\n\n\n<p>In case we are trying to open a file that is not present in the mentioned path then we will get a <code>FileNotFoundError<\/code>.<\/p>\n\n\n<pre id=\"syntax\" class=\"wp-block-code language-python\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">fp = open(<span class=\"hljs-string\">r'E:\\demos\\files\\reports.txt'<\/span>, <span class=\"hljs-string\">'r'<\/span>)\nprint(f.read())<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">FileNotFoundError: [Errno 2] No such file or directory: 'E:\\demos\\files\\reports.txt'<\/pre>\n\n\n\n<p>We can handle the file not found error inside the try-except block. Let us see an example for the same. Use except block to specify the action to be taken when the specified file is not present.<\/p>\n\n\n<div class=\"hljstoolbar\"><pre id=\"code3\"  id=\"norun\" class=\"wp-block-code language-python\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">try<\/span>:\n    fp = open(<span class=\"hljs-string\">r'E:\\PYnative\\reports\\samples.txt'<\/span>, <span class=\"hljs-string\">'r'<\/span>)\n    print(fp.read())\n    fp.close()\n<span class=\"hljs-keyword\">except<\/span> IOError:\n    print(<span class=\"hljs-string\">\"File not found. Please check the path.\"<\/span>)\n<span class=\"hljs-keyword\">finally<\/span>:\n    print(<span class=\"hljs-string\">\"Exit\"<\/span>)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre><button class=\"hljs-copy-button\" onclick=\"copy_code('code3', this);\"><i class=\"far fa-copy1\" aria-hidden=\"true\"><\/i><\/button><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">File not found. Please check the path.\nExit<\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-file-open-function\">File open() function <\/h2>\n\n\n\n<p>Python provides a set of inbuilt functions available in the interpreter, and it is always available. We don&#8217;t have to import any module for that. We can open a file using the built-in function <a href=\"https:\/\/docs.python.org\/3\/library\/functions.html#open\" target=\"_blank\" rel=\"noreferrer noopener\">open()<\/a>.<\/p>\n\n\n\n<p>Syntax of the file <code>open()<\/code> function<\/p>\n\n\n<pre id=\"syntax\" class=\"wp-block-code language-python\" aria-describedby=\"shcb-language-5\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">open(file, mode=<span class=\"hljs-string\">'r'<\/span>, buffering=<span class=\"hljs-number\">-1<\/span>, encoding=<span class=\"hljs-literal\">None<\/span>, errors=<span class=\"hljs-literal\">None<\/span>, newline=<span class=\"hljs-literal\">None<\/span>, closefd=<span class=\"hljs-literal\">True<\/span>, opener=<span class=\"hljs-literal\">None<\/span>)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>It return the <a href=\"https:\/\/pynative.com\/python-file-objects\/\">file object<\/a> which we can sue to read or write to a file.<\/p>\n\n\n\n<p><strong>Parameters<\/strong>:<\/p>\n\n\n\n<p>Let us see the parameters we can pass to the <code>open()<\/code> function to enhance the file operation.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Parameter<\/th><th>Description<\/th><\/tr><\/thead><tbody><tr><td><code>file<\/code><\/td><td>This parameter value gives the pathname (absolute or relative to the current working directory) of the file to be opened.<\/td><\/tr><tr><td><code>mode<\/code><\/td><td>This is the optional string that specifies the mode in which a file will be opened. The default value is <code>'r'<\/code> for reading a text file. We can discuss the other modes in the later section.<\/td><\/tr><tr><td><code>buffering<\/code><\/td><td>This is an optional integer used to set the buffering policy. Pass 0 to switch buffering off (only allowed in binary mode), 1 to select line buffering (only usable in text mode), and an integer &gt; 1 to indicate the size in bytes of a fixed-size chunk buffer.&nbsp;<\/td><\/tr><tr><td><code>encoding<\/code><\/td><td>This is the name of the encoding used to decode or encode the file.&nbsp;The default one is platform dependant.<\/td><\/tr><tr><td><code>errors<\/code><\/td><td>These are optional string denotes how the standard encoding and decoding errors have to be handled.<\/td><\/tr><tr><td><code>newline<\/code><\/td><td>This is the parameter that indicates how the newline mode works (it only applies to text mode). It can be&nbsp;<code>None<\/code>,&nbsp;<code>''<\/code>,&nbsp;<code>'\\n'<\/code>,&nbsp;<code>'\\r'<\/code>, and&nbsp;<code>'\\r\\n'<\/code>.<\/td><\/tr><tr><td><code>closefd<\/code><\/td><td>This parameter indicates whether to close a file descriptor or not. The default value is True. If <code>closefd<\/code>&nbsp;is&nbsp;<code>False<\/code>&nbsp;and a file descriptor rather than a filename was given, the underlying file descriptor will be kept open when the file is closed.<\/td><\/tr><\/tbody><\/table><figcaption>file open() function parameters<\/figcaption><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-opening-a-file-in-read-mode\">Opening a File in Read mode<\/h2>\n\n\n\n<p>We can open a file for reading the contents of a file using the <code>open()<\/code> function and passing<strong> the <code>r<\/code> mode<\/strong>. This will open the file only for reading the contents, and we can&#8217;t use it for anything else like writing new content.<\/p>\n\n\n\n<p>The file can basically in two categories namely flat files and non flat files. <\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Flat files are the ones that are not properly indexed, like .csv (comma separated values), where each record has different comma-separated values. But they are not ordered with an index. They generally have one record per line and in general, have a fixed set of values in each record.<\/li><li>Nonflat files are the ones with proper index values. Each record will have one index value, and we can easily find one using the index value. <\/li><\/ul>\n\n\n\n<p>Consider that we are having a file called &#8216;sample.txt&#8217; and we are opening the file for reading its contents.<\/p>\n\n\n<div class=\"hljstoolbar\"><pre id=\"code4\"  id=\"norun\" class=\"wp-block-code language-python\" aria-describedby=\"shcb-language-6\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">try<\/span>:\n    fp = open(<span class=\"hljs-string\">\"sample.txt\"<\/span>, <span class=\"hljs-string\">\"r\"<\/span>)\n    <span class=\"hljs-comment\"># Reading the contents of the file and closing<\/span>\n    print(fp.read())\n    fp.close()\n<span class=\"hljs-keyword\">except<\/span> IOError:\n    print(<span class=\"hljs-string\">\"Please check the path.\"<\/span>)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-6\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre><button class=\"hljs-copy-button\" onclick=\"copy_code('code4', this);\"><i class=\"far fa-copy1\" aria-hidden=\"true\"><\/i><\/button><\/div>\n\n\n<p id=\"h-output\"><strong>Output<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">Welcome to PYnative.com\nThis is a sample.txt<\/pre>\n\n\n\n<p><strong>Read More<\/strong>: Complete Guide on <a href=\"https:\/\/pynative.com\/python-read-file\/\">Reading Files in Python<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-opening-a-file-in-write-mode\">Opening a File in Write Mode<\/h2>\n\n\n\n<p>We can open a file for writing new contents into a file using the open() function with<strong> <code>w<\/code> as the access mode<\/strong>. The cursor or the file pointer will be placed at the <strong>beginning of the file<\/strong>.<\/p>\n\n\n\n<p><strong>Note<\/strong>: If the file is already present it will truncate the file, which means all the content previously in the file will be deleted, and the new content will be added to the file. <\/p>\n\n\n<div class=\"hljstoolbar\"><pre id=\"code5\"  id=\"norun\" class=\"wp-block-code language-python\" aria-describedby=\"shcb-language-7\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">fp = open(<span class=\"hljs-string\">\"sample2.txt\"<\/span>, <span class=\"hljs-string\">\"w\"<\/span>)\n<span class=\"hljs-comment\"># Writing content<\/span>\nfp.write(<span class=\"hljs-string\">\"New line\"<\/span>)\n\n<span class=\"hljs-comment\"># Opening the file again for reading the content<\/span>\nfp = open(<span class=\"hljs-string\">\"sample2.txt\"<\/span>, <span class=\"hljs-string\">\"r\"<\/span>)\n\n<span class=\"hljs-comment\"># Reading the contents of the file and closing<\/span>\nprint(fp.read())\nfp.close()<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-7\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre><button class=\"hljs-copy-button\" onclick=\"copy_code('code5', this);\"><i class=\"far fa-copy1\" aria-hidden=\"true\"><\/i><\/button><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">New line<\/pre>\n\n\n\n<p><strong>Read More<\/strong>: Complete Guide on <a href=\"https:\/\/pynative.com\/python-write-file\/\">Write to File in Python<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-opening-a-file-in-append-mode\">Opening a File in Append Mode<\/h2>\n\n\n\n<p>We can append some content at the end of the file using the <code>open()<\/code> function by passing the character <strong><code>a<\/code> as the access mode<\/strong>. The cursor will be placed <strong>at the end of the file<\/strong>, and the new content will get added at the end.<\/p>\n\n\n\n<p>The difference between this and the write mode is that the file&#8217;s content will not be truncated or deleted in this mode.<\/p>\n\n\n\n<p>Consider that the file &#8220;sample2.txt&#8221; is already created and there is some content in the file. Now we are opening the file in the append mode and trying to add some content at the end of the file.<\/p>\n\n\n<div class=\"hljstoolbar\"><pre id=\"code6\"  id=\"norun\" class=\"wp-block-code language-python\" aria-describedby=\"shcb-language-8\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-comment\"># Open and Append at last<\/span>\nfp = open(<span class=\"hljs-string\">\"sample2.txt\"<\/span>, <span class=\"hljs-string\">\"a\"<\/span>)\nfp.write(<span class=\"hljs-string\">\" Added this line by opening the file in append mode \"<\/span>)\n\n<span class=\"hljs-comment\"># Opening the file again to read<\/span>\nfp = open(<span class=\"hljs-string\">\"sample2.txt\"<\/span>, <span class=\"hljs-string\">\"r\"<\/span>)\nprint(fp.read())\nfp.close()<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-8\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre><button class=\"hljs-copy-button\" onclick=\"copy_code('code6', this);\"><i class=\"far fa-copy1\" aria-hidden=\"true\"><\/i><\/button><\/div>\n\n\n<div class=\"wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex\">\n<div class=\"wp-block-column is-layout-flow wp-block-column-is-layout-flow\">\n<p><strong>Output<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">New line\nAdded this line by opening a file in the append mode <\/pre>\n<\/div>\n\n\n\n<div class=\"wp-block-column is-layout-flow wp-block-column-is-layout-flow\">\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"461\" height=\"343\" src=\"https:\/\/pynative.com\/wp-content\/uploads\/2021\/06\/sample2_txt_write_append.png\" alt=\"sample text file after writing\" class=\"wp-image-9574\" srcset=\"https:\/\/pynative.com\/wp-content\/uploads\/2021\/06\/sample2_txt_write_append.png 461w, https:\/\/pynative.com\/wp-content\/uploads\/2021\/06\/sample2_txt_write_append-300x223.png 300w\" sizes=\"auto, (max-width: 461px) 100vw, 461px\" \/><figcaption>sample text file after writing<\/figcaption><\/figure><\/div>\n<\/div>\n<\/div>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-closing-a-file\">Closing a File <\/h2>\n\n\n\n<p>We need to make sure that the file will be closed properly after completing the file operation. It is a bad practice to leave your files open.<\/p>\n\n\n\n<p>In Python, It is very important to close a file once the job is done mainly for the following reasons: &#8211;<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>It releases the resources that have been tied up with the file. By this space in the RAM can be better utilized and ensures a better performance.<\/li><li>It ensures better garbage collection.<\/li><li>There is a limit to the number of open files in an application. It is always better to close the file to ensure that the limit is not crossed.<\/li><li>If you open the file in write or read-write mode, you don&#8217;t know when data is flushed.<\/li><\/ul>\n\n\n\n<p>A file can be closed just by calling the <code>close()<\/code> function as follows.<\/p>\n\n\n<div class=\"hljstoolbar\"><pre id=\"code7\"  id=\"norun\" class=\"wp-block-code language-python\" aria-describedby=\"shcb-language-9\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-comment\"># Opening the file to read the contents<\/span>\nf = open(<span class=\"hljs-string\">\"sample2.txt\"<\/span>, <span class=\"hljs-string\">\"r\"<\/span>)\nprint(f.read())\n\n<span class=\"hljs-comment\"># Closing the file once our job is done<\/span>\nf.close()<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-9\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre><button class=\"hljs-copy-button\" onclick=\"copy_code('code7', this);\"><i class=\"far fa-copy1\" aria-hidden=\"true\"><\/i><\/button><\/div>\n\n\n<h2 class=\"wp-block-heading\" id=\"h-opening-file-using-with-statement\">Opening file using <code>with<\/code> statement<\/h2>\n\n\n\n<p>We can open a file using the <a href=\"https:\/\/www.python.org\/dev\/peps\/pep-0343\/\" target=\"_blank\" rel=\"noreferrer noopener\">with statement<\/a> along with the open function. The general syntax is as follows.<\/p>\n\n\n<pre id=\"syntax\" class=\"wp-block-code language-python\" aria-describedby=\"shcb-language-10\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">with<\/span> open(__file__, accessmode) <span class=\"hljs-keyword\">as<\/span> f:<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-10\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>The following are the main advantages of opening a file using the <code>with<\/code> statement<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>The with statement simplifies exception handling by encapsulating common preparation and cleanup tasks.<\/li><li>This also ensures that a file is automatically closed after leaving the block.<\/li><li>As the <strong>file is closed automatically<\/strong> it ensures that all the resources that are tied up with the file are released. <\/li><\/ul>\n\n\n\n<p>Let us see how we can the with statement for opening a file with an example. Consider there are two files &#8216;sample.txt&#8217; and &#8216;sample2.txt&#8217; and we want to copy the contents of the first file to the second.<\/p>\n\n\n<div class=\"hljstoolbar\"><pre id=\"code8\"  id=\"norun\" class=\"wp-block-code language-python\" aria-describedby=\"shcb-language-11\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-comment\"># Opening file<\/span>\n<span class=\"hljs-keyword\">with<\/span> open(<span class=\"hljs-string\">'sample.txt'<\/span>, <span class=\"hljs-string\">'r'<\/span>, encoding=<span class=\"hljs-string\">'utf-8'<\/span>) <span class=\"hljs-keyword\">as<\/span> infile, open(<span class=\"hljs-string\">'sample2.txt'<\/span>, <span class=\"hljs-string\">'w'<\/span>) <span class=\"hljs-keyword\">as<\/span> outfile:\n    <span class=\"hljs-comment\"># read sample.txt an and write its content into sample2.txt<\/span>\n    <span class=\"hljs-keyword\">for<\/span> line <span class=\"hljs-keyword\">in<\/span> infile:\n        outfile.write(line)\n\n<span class=\"hljs-comment\"># Opening the file to read the contents<\/span>\nf = open(<span class=\"hljs-string\">\"Sample2.txt\"<\/span>, <span class=\"hljs-string\">\"r\"<\/span>)\nprint(f.read())\nf.close()<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-11\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre><button class=\"hljs-copy-button\" onclick=\"copy_code('code8', this);\"><i class=\"far fa-copy1\" aria-hidden=\"true\"><\/i><\/button><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">Welcome to PYnative.com\nFile created to demonstrate file handling in Python<\/pre>\n\n\n\n<p>Here we can see that the contents of the sample2.txt has been replaced by the contents of sample.txt.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-creating-a-new-file\">Creating a new file<\/h2>\n\n\n\n<p>We can <a href=\"https:\/\/pynative.com\/python-create-file\/\">create a new file<\/a> using the <code>open()<\/code> function by setting <strong>the <code>x<\/code> mode<\/strong>. This method will ensure that the file doesn&#8217;t already exist and then create a new file. It will raise the <code>FileExistsError<\/code> if the file already exists.<\/p>\n\n\n\n<p><strong>Example<\/strong>: Creating a new file.<\/p>\n\n\n<div class=\"hljstoolbar\"><pre id=\"code9\"  id=\"norun\" class=\"wp-block-code language-python\" aria-describedby=\"shcb-language-12\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">try<\/span>:\n    <span class=\"hljs-comment\"># Creating a new file<\/span>\n    <span class=\"hljs-keyword\">with<\/span> open(<span class=\"hljs-string\">\"sample3.txt\"<\/span>, <span class=\"hljs-string\">\"x\"<\/span>) <span class=\"hljs-keyword\">as<\/span> fp:\n        fp.write(<span class=\"hljs-string\">\"Hello World! I am a new file\"<\/span>)\n\n    <span class=\"hljs-comment\"># reading the contents of the new file<\/span>\n    fp = open(<span class=\"hljs-string\">\"sample3.txt\"<\/span>, <span class=\"hljs-string\">\"r\"<\/span>)\n    print(fp.read())\n<span class=\"hljs-keyword\">except<\/span> FileExistsError:\n    print(<span class=\"hljs-string\">\"The file already exists\"<\/span>)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-12\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre><button class=\"hljs-copy-button\" onclick=\"copy_code('code9', this);\"><i class=\"far fa-copy1\" aria-hidden=\"true\"><\/i><\/button><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">Hello World! I am a new file<\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-opening-a-file-for-multiple-operations\">Opening a File for multiple operations<\/h2>\n\n\n\n<p>In Python, we can open a file for performing multiple operations simultaneously by using the <code>'+'<\/code> operator. When we pass <code>r+<\/code> mode then it will enable both reading and writing options in the file. Let us see this with an example.<\/p>\n\n\n<div class=\"hljstoolbar\"><pre id=\"code10\"  id=\"norun\" class=\"wp-block-code language-python\" aria-describedby=\"shcb-language-13\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">with<\/span> open(<span class=\"hljs-string\">\"Sample3.txt\"<\/span>, <span class=\"hljs-string\">\"r+\"<\/span>) <span class=\"hljs-keyword\">as<\/span> fp:\n    <span class=\"hljs-comment\"># reading the contents before writing<\/span>\n    print(fp.read())\n\n    <span class=\"hljs-comment\"># Writing new content to this file<\/span>\n    fp.write(<span class=\"hljs-string\">\"\\nAdding this new content\"<\/span>)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-13\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre><button class=\"hljs-copy-button\" onclick=\"copy_code('code10', this);\"><i class=\"far fa-copy1\" aria-hidden=\"true\"><\/i><\/button><\/div>\n\n\n<h2 class=\"wp-block-heading\" id=\"h-opening-a-binary-file\">Opening a Binary file<\/h2>\n\n\n\n<p>Binary files are basically the ones with data in the Byte format (0&#8217;s and 1&#8217;s). This generally doesn&#8217;t contain the EOL(End of Line) so it is important to check that condition before reading the contents of the file.<\/p>\n\n\n\n<p>We can open and read the contents of the binary file as below.<\/p>\n\n\n<div class=\"hljstoolbar\"><pre id=\"code11\"  id=\"norun\" class=\"wp-block-code language-python\" aria-describedby=\"shcb-language-14\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">with<\/span> open(<span class=\"hljs-string\">\"sample.bin\"<\/span>, <span class=\"hljs-string\">\"rb\"<\/span>) <span class=\"hljs-keyword\">as<\/span> f:\n    byte_content = f.read(<span class=\"hljs-number\">1<\/span>)\n    <span class=\"hljs-keyword\">while<\/span> byte_content:\n        <span class=\"hljs-comment\"># Printing the contents of the file<\/span>\n        print(byte_content)\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-14\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre><button class=\"hljs-copy-button\" onclick=\"copy_code('code11', this);\"><i class=\"far fa-copy1\" aria-hidden=\"true\"><\/i><\/button><\/div>\n\n\n<h2 class=\"wp-block-heading\" id=\"h-summary\">Summary<\/h2>\n\n\n\n<p>In this tutorial, we have covered how to open a file using the different access modes. Also, we learned the importance of opening a file using the &#8216;with&#8217; statement.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this tutorial, you&#8217;ll learn how to open a file in Python. The data can be in the form of files such as text, csv, and binary files. To extract data from these files, Python comes with built-in functions to open a file and then read and write the file&#8217;s contents. After reading this tutorial, [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":9572,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_genesis_hide_title":false,"_genesis_hide_breadcrumbs":false,"_genesis_hide_singular_image":false,"_genesis_hide_footer_widgets":false,"_genesis_custom_body_class":"","_genesis_custom_post_class":"","_genesis_layout":"","footnotes":""},"categories":[22,33],"tags":[34],"class_list":{"0":"post-9549","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-python","8":"category-file-handling","9":"tag-file-handling","10":"entry"},"yoast_head":"<!-- This site is optimized with the Yoast SEO Premium plugin v27.3 (Yoast SEO v27.3) - https:\/\/yoast.com\/product\/yoast-seo-premium-wordpress\/ -->\n<title>Open a File in Python &#8211; PYnative<\/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:\/\/pynative.com\/python-file-open\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Open a File in Python\" \/>\n<meta property=\"og:description\" content=\"In this tutorial, you&#8217;ll learn how to open a file in Python. The data can be in the form of files such as text, csv, and binary files. To extract data from these files, Python comes with built-in functions to open a file and then read and write the file&#8217;s contents. After reading this tutorial, [&hellip;]\" \/>\n<meta property=\"og:url\" content=\"https:\/\/pynative.com\/python-file-open\/\" \/>\n<meta property=\"og:site_name\" content=\"PYnative\" \/>\n<meta property=\"article:published_time\" content=\"2021-06-13T12:02:18+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2021-07-25T05:58:42+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/pynative.com\/wp-content\/uploads\/2021\/06\/python-file-open.png\" \/>\n\t<meta property=\"og:image:width\" content=\"1291\" \/>\n\t<meta property=\"og:image:height\" content=\"680\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Vishal\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@PyNative\" \/>\n<meta name=\"twitter:site\" content=\"@PyNative\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Vishal\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"11 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/pynative.com\\\/python-file-open\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/pynative.com\\\/python-file-open\\\/\"},\"author\":{\"name\":\"Vishal\",\"@id\":\"https:\\\/\\\/pynative.com\\\/#\\\/schema\\\/person\\\/64b55d5bde2265918c5a9931de4de71f\"},\"headline\":\"Open a File in Python\",\"datePublished\":\"2021-06-13T12:02:18+00:00\",\"dateModified\":\"2021-07-25T05:58:42+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/pynative.com\\\/python-file-open\\\/\"},\"wordCount\":1901,\"commentCount\":4,\"publisher\":{\"@id\":\"https:\\\/\\\/pynative.com\\\/#\\\/schema\\\/person\\\/64b55d5bde2265918c5a9931de4de71f\"},\"image\":{\"@id\":\"https:\\\/\\\/pynative.com\\\/python-file-open\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/pynative.com\\\/wp-content\\\/uploads\\\/2021\\\/06\\\/python-file-open.png\",\"keywords\":[\"File Handling\"],\"articleSection\":[\"Python\",\"Python File Handling\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/pynative.com\\\/python-file-open\\\/#respond\"]}],\"accessibilityFeature\":[\"tableOfContents\"]},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/pynative.com\\\/python-file-open\\\/\",\"url\":\"https:\\\/\\\/pynative.com\\\/python-file-open\\\/\",\"name\":\"Open a File in Python &#8211; PYnative\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/pynative.com\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/pynative.com\\\/python-file-open\\\/#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/pynative.com\\\/python-file-open\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/pynative.com\\\/wp-content\\\/uploads\\\/2021\\\/06\\\/python-file-open.png\",\"datePublished\":\"2021-06-13T12:02:18+00:00\",\"dateModified\":\"2021-07-25T05:58:42+00:00\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/pynative.com\\\/python-file-open\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/pynative.com\\\/python-file-open\\\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/pynative.com\\\/python-file-open\\\/#primaryimage\",\"url\":\"https:\\\/\\\/pynative.com\\\/wp-content\\\/uploads\\\/2021\\\/06\\\/python-file-open.png\",\"contentUrl\":\"https:\\\/\\\/pynative.com\\\/wp-content\\\/uploads\\\/2021\\\/06\\\/python-file-open.png\",\"width\":1291,\"height\":680,\"caption\":\"Open a file in Python\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/pynative.com\\\/python-file-open\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/pynative.com\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Python\",\"item\":\"https:\\\/\\\/pynative.com\\\/python\\\/\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"File Handling\",\"item\":\"https:\\\/\\\/pynative.com\\\/python\\\/file-handling\\\/\"},{\"@type\":\"ListItem\",\"position\":4,\"name\":\"Open a File in Python\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/pynative.com\\\/#website\",\"url\":\"https:\\\/\\\/pynative.com\\\/\",\"name\":\"PYnative\",\"description\":\"Python Programming\",\"publisher\":{\"@id\":\"https:\\\/\\\/pynative.com\\\/#\\\/schema\\\/person\\\/64b55d5bde2265918c5a9931de4de71f\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/pynative.com\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":[\"Person\",\"Organization\"],\"@id\":\"https:\\\/\\\/pynative.com\\\/#\\\/schema\\\/person\\\/64b55d5bde2265918c5a9931de4de71f\",\"name\":\"Vishal\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/pynative.com\\\/wp-content\\\/uploads\\\/2019\\\/01\\\/vishalHule.jpg\",\"url\":\"https:\\\/\\\/pynative.com\\\/wp-content\\\/uploads\\\/2019\\\/01\\\/vishalHule.jpg\",\"contentUrl\":\"https:\\\/\\\/pynative.com\\\/wp-content\\\/uploads\\\/2019\\\/01\\\/vishalHule.jpg\",\"width\":968,\"height\":1065,\"caption\":\"Vishal\"},\"logo\":{\"@id\":\"https:\\\/\\\/pynative.com\\\/wp-content\\\/uploads\\\/2019\\\/01\\\/vishalHule.jpg\"},\"description\":\"Founder of PYnative.com. I am a Python developer and I love to write articles to help developers. | All the best for your future Python endeavors!\",\"sameAs\":[\"https:\\\/\\\/pynative.com\"]},{\"@type\":\"HowTo\",\"@id\":\"https:\\\/\\\/pynative.com\\\/python-file-open\\\/#howto-1\",\"name\":\"Open a File in Python\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/pynative.com\\\/python-file-open\\\/#article\"},\"description\":\"To open a file in Python, Please follow these steps:\",\"step\":[{\"@type\":\"HowToStep\",\"url\":\"https:\\\/\\\/pynative.com\\\/python-file-open\\\/#how-to-step-1623071602523\",\"name\":\"Find the path of a file\",\"itemListElement\":[{\"@type\":\"HowToDirection\",\"text\":\"We can open a file using both relative path and absolute path. The path is the location of the file on the disk.An absolute path contains the complete directory list required to locate the file.A relative path contains the current directory and then the file name.\"}]},{\"@type\":\"HowToStep\",\"url\":\"https:\\\/\\\/pynative.com\\\/python-file-open\\\/#how-to-step-1623072196137\",\"name\":\"Decide the access mode\",\"itemListElement\":[{\"@type\":\"HowToDirection\",\"text\":\"The access mode specifies the operation you wanted to perform on the file, such as reading or writing. To open and read a file, use the r access mode. To open a file for writing, use the w mode.\"}]},{\"@type\":\"HowToStep\",\"url\":\"https:\\\/\\\/pynative.com\\\/python-file-open\\\/#how-to-step-1623072223707\",\"name\":\"Pass file path and access mode to the open() function\",\"itemListElement\":[{\"@type\":\"HowToDirection\",\"text\":\"fp= open(r\\\"File_Name\\\", \\\"Access_Mode\\\").  For example, to open and read: fp = open('sample.txt', 'r')\"}]},{\"@type\":\"HowToStep\",\"url\":\"https:\\\/\\\/pynative.com\\\/python-file-open\\\/#how-to-step-1623072253286\",\"name\":\"Read content from a file.\",\"itemListElement\":[{\"@type\":\"HowToDirection\",\"text\":\"Next, read a file using the read() method. For example, content = fp.read(). You can also use readline(), and readlines()\"}]},{\"@type\":\"HowToStep\",\"url\":\"https:\\\/\\\/pynative.com\\\/python-file-open\\\/#how-to-step-1623072256024\",\"name\":\"Write content into the file\",\"itemListElement\":[{\"@type\":\"HowToDirection\",\"text\":\"If you have opened a file in a write mode, you can write or append text to the file using the write() method. For example, fp.write('content'). You can also use the writeine() method.\"}]},{\"@type\":\"HowToStep\",\"url\":\"https:\\\/\\\/pynative.com\\\/python-file-open\\\/#how-to-step-1623073790009\",\"name\":\"Close file after completing operation\",\"itemListElement\":[{\"@type\":\"HowToDirection\",\"text\":\"We need to make sure that the file will be closed properly after completing the file operation. Use fp.close() to close a file.\"}]}],\"inLanguage\":\"en-US\"}]}<\/script>\n<!-- \/ Yoast SEO Premium plugin. -->","yoast_head_json":{"title":"Open a File in Python &#8211; PYnative","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:\/\/pynative.com\/python-file-open\/","og_locale":"en_US","og_type":"article","og_title":"Open a File in Python","og_description":"In this tutorial, you&#8217;ll learn how to open a file in Python. The data can be in the form of files such as text, csv, and binary files. To extract data from these files, Python comes with built-in functions to open a file and then read and write the file&#8217;s contents. After reading this tutorial, [&hellip;]","og_url":"https:\/\/pynative.com\/python-file-open\/","og_site_name":"PYnative","article_published_time":"2021-06-13T12:02:18+00:00","article_modified_time":"2021-07-25T05:58:42+00:00","og_image":[{"width":1291,"height":680,"url":"https:\/\/pynative.com\/wp-content\/uploads\/2021\/06\/python-file-open.png","type":"image\/png"}],"author":"Vishal","twitter_card":"summary_large_image","twitter_creator":"@PyNative","twitter_site":"@PyNative","twitter_misc":{"Written by":"Vishal","Est. reading time":"11 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/pynative.com\/python-file-open\/#article","isPartOf":{"@id":"https:\/\/pynative.com\/python-file-open\/"},"author":{"name":"Vishal","@id":"https:\/\/pynative.com\/#\/schema\/person\/64b55d5bde2265918c5a9931de4de71f"},"headline":"Open a File in Python","datePublished":"2021-06-13T12:02:18+00:00","dateModified":"2021-07-25T05:58:42+00:00","mainEntityOfPage":{"@id":"https:\/\/pynative.com\/python-file-open\/"},"wordCount":1901,"commentCount":4,"publisher":{"@id":"https:\/\/pynative.com\/#\/schema\/person\/64b55d5bde2265918c5a9931de4de71f"},"image":{"@id":"https:\/\/pynative.com\/python-file-open\/#primaryimage"},"thumbnailUrl":"https:\/\/pynative.com\/wp-content\/uploads\/2021\/06\/python-file-open.png","keywords":["File Handling"],"articleSection":["Python","Python File Handling"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/pynative.com\/python-file-open\/#respond"]}],"accessibilityFeature":["tableOfContents"]},{"@type":"WebPage","@id":"https:\/\/pynative.com\/python-file-open\/","url":"https:\/\/pynative.com\/python-file-open\/","name":"Open a File in Python &#8211; PYnative","isPartOf":{"@id":"https:\/\/pynative.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/pynative.com\/python-file-open\/#primaryimage"},"image":{"@id":"https:\/\/pynative.com\/python-file-open\/#primaryimage"},"thumbnailUrl":"https:\/\/pynative.com\/wp-content\/uploads\/2021\/06\/python-file-open.png","datePublished":"2021-06-13T12:02:18+00:00","dateModified":"2021-07-25T05:58:42+00:00","breadcrumb":{"@id":"https:\/\/pynative.com\/python-file-open\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/pynative.com\/python-file-open\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/pynative.com\/python-file-open\/#primaryimage","url":"https:\/\/pynative.com\/wp-content\/uploads\/2021\/06\/python-file-open.png","contentUrl":"https:\/\/pynative.com\/wp-content\/uploads\/2021\/06\/python-file-open.png","width":1291,"height":680,"caption":"Open a file in Python"},{"@type":"BreadcrumbList","@id":"https:\/\/pynative.com\/python-file-open\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/pynative.com\/"},{"@type":"ListItem","position":2,"name":"Python","item":"https:\/\/pynative.com\/python\/"},{"@type":"ListItem","position":3,"name":"File Handling","item":"https:\/\/pynative.com\/python\/file-handling\/"},{"@type":"ListItem","position":4,"name":"Open a File in Python"}]},{"@type":"WebSite","@id":"https:\/\/pynative.com\/#website","url":"https:\/\/pynative.com\/","name":"PYnative","description":"Python Programming","publisher":{"@id":"https:\/\/pynative.com\/#\/schema\/person\/64b55d5bde2265918c5a9931de4de71f"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/pynative.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":["Person","Organization"],"@id":"https:\/\/pynative.com\/#\/schema\/person\/64b55d5bde2265918c5a9931de4de71f","name":"Vishal","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/pynative.com\/wp-content\/uploads\/2019\/01\/vishalHule.jpg","url":"https:\/\/pynative.com\/wp-content\/uploads\/2019\/01\/vishalHule.jpg","contentUrl":"https:\/\/pynative.com\/wp-content\/uploads\/2019\/01\/vishalHule.jpg","width":968,"height":1065,"caption":"Vishal"},"logo":{"@id":"https:\/\/pynative.com\/wp-content\/uploads\/2019\/01\/vishalHule.jpg"},"description":"Founder of PYnative.com. I am a Python developer and I love to write articles to help developers. | All the best for your future Python endeavors!","sameAs":["https:\/\/pynative.com"]},{"@type":"HowTo","@id":"https:\/\/pynative.com\/python-file-open\/#howto-1","name":"Open a File in Python","mainEntityOfPage":{"@id":"https:\/\/pynative.com\/python-file-open\/#article"},"description":"To open a file in Python, Please follow these steps:","step":[{"@type":"HowToStep","url":"https:\/\/pynative.com\/python-file-open\/#how-to-step-1623071602523","name":"Find the path of a file","itemListElement":[{"@type":"HowToDirection","text":"We can open a file using both relative path and absolute path. The path is the location of the file on the disk.An absolute path contains the complete directory list required to locate the file.A relative path contains the current directory and then the file name."}]},{"@type":"HowToStep","url":"https:\/\/pynative.com\/python-file-open\/#how-to-step-1623072196137","name":"Decide the access mode","itemListElement":[{"@type":"HowToDirection","text":"The access mode specifies the operation you wanted to perform on the file, such as reading or writing. To open and read a file, use the r access mode. To open a file for writing, use the w mode."}]},{"@type":"HowToStep","url":"https:\/\/pynative.com\/python-file-open\/#how-to-step-1623072223707","name":"Pass file path and access mode to the open() function","itemListElement":[{"@type":"HowToDirection","text":"fp= open(r\"File_Name\", \"Access_Mode\").  For example, to open and read: fp = open('sample.txt', 'r')"}]},{"@type":"HowToStep","url":"https:\/\/pynative.com\/python-file-open\/#how-to-step-1623072253286","name":"Read content from a file.","itemListElement":[{"@type":"HowToDirection","text":"Next, read a file using the read() method. For example, content = fp.read(). You can also use readline(), and readlines()"}]},{"@type":"HowToStep","url":"https:\/\/pynative.com\/python-file-open\/#how-to-step-1623072256024","name":"Write content into the file","itemListElement":[{"@type":"HowToDirection","text":"If you have opened a file in a write mode, you can write or append text to the file using the write() method. For example, fp.write('content'). You can also use the writeine() method."}]},{"@type":"HowToStep","url":"https:\/\/pynative.com\/python-file-open\/#how-to-step-1623073790009","name":"Close file after completing operation","itemListElement":[{"@type":"HowToDirection","text":"We need to make sure that the file will be closed properly after completing the file operation. Use fp.close() to close a file."}]}],"inLanguage":"en-US"}]}},"featured_image_src":"https:\/\/pynative.com\/wp-content\/uploads\/2021\/06\/python-file-open-600x400.png","featured_image_src_square":"https:\/\/pynative.com\/wp-content\/uploads\/2021\/06\/python-file-open-600x600.png","author_info":{"display_name":"Vishal","author_link":"https:\/\/pynative.com\/author\/vishal\/"},"_links":{"self":[{"href":"https:\/\/pynative.com\/wp-json\/wp\/v2\/posts\/9549","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/pynative.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/pynative.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/pynative.com\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/pynative.com\/wp-json\/wp\/v2\/comments?post=9549"}],"version-history":[{"count":0,"href":"https:\/\/pynative.com\/wp-json\/wp\/v2\/posts\/9549\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/pynative.com\/wp-json\/wp\/v2\/media\/9572"}],"wp:attachment":[{"href":"https:\/\/pynative.com\/wp-json\/wp\/v2\/media?parent=9549"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/pynative.com\/wp-json\/wp\/v2\/categories?post=9549"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/pynative.com\/wp-json\/wp\/v2\/tags?post=9549"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}