

{"id":8130,"date":"2018-02-15T09:10:36","date_gmt":"2018-02-15T03:40:36","guid":{"rendered":"https:\/\/data-flair.training\/blogs\/?p=8130"},"modified":"2026-04-22T15:11:04","modified_gmt":"2026-04-22T09:41:04","slug":"python-file","status":"publish","type":"post","link":"https:\/\/data-flair.training\/blogs\/python-file\/","title":{"rendered":"Python File i\/o &#8211; Python Write to File and Python Read File"},"content":{"rendered":"<p>An important component of an operating system is its file and directories. We\u2019ve talked about Python Directories.<\/p>\n<p>In that, we learned to manipulate (create, rename, delete,..) directories.<\/p>\n<p>Today, we will talk about Python file I\/O. After this lesson, you will be able to Python open file, Python close file, Python read file, and Python writes to file.<\/p>\n<p>Let\u2019s begin.<\/p>\n<h3>What is Python File?<\/h3>\n<p>A file is a location on disk that stores related information and has a name. A hard-disk is non-volatile, and we use files to organize our data in different directories on a hard-disk.<\/p>\n<p>The RAM (Random Access Memory) is volatile; it holds data only as long as it is up. So, we use files to store data permanently.<\/p>\n<p>To read from or write to a file, we must first open it. And then when we\u2019re done with it, we should close it to free up the resources it holds (Open, Read\/Write, Close).<\/p>\n<h3>Python Open File<\/h3>\n<p>To start Python file i\/o, we deal with files and have a few in-built functions and methods in Python. To open a file in Python, we use the read() method.<\/p>\n<p>But first, let\u2019s get to the desktop, and choose a file to work with.<\/p>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; import os\r\n&gt;&gt;&gt; os.getcwd()<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>&#8216;C:\\\\Users\\\\lifei\\\\AppData\\\\Local\\\\Programs\\\\Python\\\\Python36-32&#8217;<\/p>\n<\/div>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; os.chdir('C:\\\\Users\\\\lifei\\\\Desktop')\r\n&gt;&gt;&gt; os.listdir()<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>[&#8216;Adobe Photoshop CS2.lnk&#8217;, &#8216;Atom.lnk&#8217;, &#8216;Backup iPhone7+ 20-1-18&#8217;, &#8216;Burn Book.txt&#8217;, &#8216;ch&#8217;, &#8216;desktop.ini&#8217;, &#8216;dmkidnap.png&#8217;, &#8216;Documents&#8217;, &#8216;Eclipse Cpp Oxygen.lnk&#8217;, &#8216;Eclipse Java Oxygen.lnk&#8217;, &#8216;Eclipse Jee Oxygen.lnk&#8217;, &#8216;gifts.jpg&#8217;, &#8216;Items for trip.txt&#8217;, &#8216;Major temp&#8217;, structure&#8217;, &#8216;office temp.jpg&#8217;, &#8216;Papers&#8217;, &#8216;Remember to remember.txt&#8217;, &#8216;To do.txt&#8217;, &#8216;Today.txt&#8217;]<\/p>\n<\/div>\n<p>If this seems new to you, be sure to check out Python Directory.<\/p>\n<p>Now, let\u2019s open Python file \u2018To do.txt\u2019.<\/p>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; open('To do.txt')<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>&lt;_io.TextIOWrapper name=&#8217;To do.txt&#8217; mode=&#8217;r&#8217; encoding=&#8217;cp1252&#8242;&gt;<\/p>\n<\/div>\n<p>But to work with this, we must store it into a Python variable. Let\u2019s do this.<\/p>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; todo=open('To do.txt')\r\n&gt;&gt;&gt; todo<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>&lt;_io.TextIOWrapper name=&#8217;To do.txt&#8217; mode=&#8217;r&#8217; encoding=&#8217;cp1252&#8242;&gt;<\/p>\n<\/div>\n<p>We wouldn\u2019t have to change directory if we just passed the full path of\u00a0Python file to open(). But let\u2019s work with this for now.<\/p>\n<div id=\"attachment_8149\" style=\"width: 1210px\" class=\"wp-caption aligncenter\"><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Python-Open-File-01-1.jpg\"><img loading=\"lazy\" decoding=\"async\" aria-describedby=\"caption-attachment-8149\" class=\"wp-image-8149 size-full\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Python-Open-File-01-1.jpg\" alt=\"Python File I\/O - Python Open File\" width=\"1200\" height=\"628\" srcset=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Python-Open-File-01-1.jpg 1200w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Python-Open-File-01-1-150x79.jpg 150w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Python-Open-File-01-1-300x157.jpg 300w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Python-Open-File-01-1-768x402.jpg 768w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Python-Open-File-01-1-1024x536.jpg 1024w\" sizes=\"auto, (max-width: 1200px) 100vw, 1200px\" \/><\/a><p id=\"caption-attachment-8149\" class=\"wp-caption-text\">Python File I\/O &#8211; Python Open File<\/p><\/div>\n<h4>1. File Modes in Python<\/h4>\n<p>While opening Python file, we can declare our intentions by choosing a mode. We have the following modes:<\/p>\n<table>\n<tbody>\n<tr>\n<td width=\"312\"><strong>Mode<\/strong><\/td>\n<td width=\"312\"><strong>Description<\/strong><\/td>\n<\/tr>\n<tr>\n<td width=\"312\">r<\/td>\n<td width=\"312\">To read a file (default)<\/td>\n<\/tr>\n<tr>\n<td width=\"312\">w<\/td>\n<td width=\"312\">To write a file; Creates a new file if it doesn\u2019t exist, truncates if it does<\/td>\n<\/tr>\n<tr>\n<td width=\"312\">x<\/td>\n<td width=\"312\">Exclusive creation; fails if a file already exists<\/td>\n<\/tr>\n<tr>\n<td width=\"312\">a<\/td>\n<td width=\"312\">To append at the end of the file; create if doesn\u2019t exist<\/td>\n<\/tr>\n<tr>\n<td width=\"312\">t<\/td>\n<td width=\"312\">Text mode (default)<\/td>\n<\/tr>\n<tr>\n<td width=\"312\">b<\/td>\n<td width=\"312\">Binary mode<\/td>\n<\/tr>\n<tr>\n<td width=\"312\">+<\/td>\n<td width=\"312\">To open a file for updating (reading or writing)<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>Let\u2019s take a couple of examples.<\/p>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; todo=open('To do.txt','r+b') #To read and write in binary mode\r\n&gt;&gt;&gt; todo=open('To do.txt','a')<\/pre>\n<h4>2. Choosing Your Encoding<\/h4>\n<p>Also, it is good practice to specify what encoding we want, because different systems use a different encoding. While Windows uses \u2018cp1252\u2019, Linux uses \u2018utf-8\u2019.<\/p>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; todo=open('To do.txt',mode='r',encoding='utf-8')<\/pre>\n<h4>3. When Python File Doesn\u2019t Exist<\/h4>\n<p>Finally, if you try opening\u00a0Python file that doesn\u2019t exist, the interpreter will throw a FileNotFoundError.<\/p>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; todo=open('abc.txt')<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>Traceback (most recent call last):File &#8220;&lt;pyshell#27&gt;&#8221;, line 1, in &lt;module&gt;<\/p>\n<p>todo=open(&#8216;abc.txt&#8217;)<\/p>\n<p>FileNotFoundError: [Errno 2] No such file or directory: &#8216;abc.txt&#8217;<\/p>\n<\/div>\n<p>Tell us how do you like the Python Open file Explanation.<\/p>\n<h3>Python Close File<\/h3>\n<p>When we tried to manually go rewrite the Python file, it threw this error dialog when we attempted to save it.<\/p>\n<p>So, remember, always close what you open:<\/p>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; todo.close()<\/pre>\n<div id=\"attachment_8150\" style=\"width: 1210px\" class=\"wp-caption aligncenter\"><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Python-Close-File-01-1.jpg\"><img loading=\"lazy\" decoding=\"async\" aria-describedby=\"caption-attachment-8150\" class=\"wp-image-8150 size-full\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Python-Close-File-01-1.jpg\" alt=\"Python File I\/O - Python Close File\" width=\"1200\" height=\"628\" srcset=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Python-Close-File-01-1.jpg 1200w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Python-Close-File-01-1-150x79.jpg 150w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Python-Close-File-01-1-300x157.jpg 300w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Python-Close-File-01-1-768x402.jpg 768w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Python-Close-File-01-1-1024x536.jpg 1024w\" sizes=\"auto, (max-width: 1200px) 100vw, 1200px\" \/><\/a><p id=\"caption-attachment-8150\" class=\"wp-caption-text\">Python File I\/O &#8211; Python Close File<\/p><\/div>\n<h4>1. Try..finally in Python<\/h4>\n<p>But if an exception occurs in the middle of our code, the file remains open, and the resources aren\u2019t freed.<\/p>\n<p>To take care of these situations, we put the close() method in the finally-block.<\/p>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; try:\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 f=open('To do.txt')\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 print(\"Before\")\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 print(1\/0)\r\nfinally:\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 f.close()<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>BeforeTraceback (most recent call last):<\/p>\n<p>File &#8220;&lt;pyshell#51&gt;&#8221;, line 4, in &lt;module&gt;<\/p>\n<p>print(1\/0)<\/p>\n<p>ZeroDivisionError: division by zero<\/p>\n<\/div>\n<h4>2. With statement in Python<\/h4>\n<p>If you think having to put close() every time you\u2019re done with a Python file is bunk, use the \u2018with\u2019 statement.<\/p>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; with open('To do.txt') as f:\r\n        f.read()<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>&#8216;Get groceries\\nOrganize room\\nPrint labels\\nWrite article\\nStudy for exam&#8217;<\/p>\n<\/div>\n<p>With this, it will close the file implicitly as soon as it finishes executing the statements under the block.<\/p>\n<h3>Python Read File<\/h3>\n<p>To read the contents of a Python file, we can do one of these:<\/p>\n<div id=\"attachment_8152\" style=\"width: 1210px\" class=\"wp-caption aligncenter\"><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Python-Read-File-01.jpg\"><img loading=\"lazy\" decoding=\"async\" aria-describedby=\"caption-attachment-8152\" class=\"wp-image-8152 size-full\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Python-Read-File-01.jpg\" alt=\"Python Read File\" width=\"1200\" height=\"628\" srcset=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Python-Read-File-01.jpg 1200w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Python-Read-File-01-150x79.jpg 150w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Python-Read-File-01-300x157.jpg 300w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Python-Read-File-01-768x402.jpg 768w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Python-Read-File-01-1024x536.jpg 1024w\" sizes=\"auto, (max-width: 1200px) 100vw, 1200px\" \/><\/a><p id=\"caption-attachment-8152\" class=\"wp-caption-text\">Python File I\/o &#8211; Python Read File<\/p><\/div>\n<h4>1. The read() Method in Python<\/h4>\n<p>We can use the read() method to read what\u2019s in a Python file.<\/p>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; with open('To do.txt') as todo:\r\n          todo.read()<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>&#8216;Get groceries\\nOrganize room\\nPrint labels\\nWrite article\\nStudy for examLearn to cook\\nLearn to cook&#8217;<\/p>\n<\/div>\n<p>When we provide an integer argument to read(), it reads that many characters from the beginning of the Python file.<\/p>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; todo=open('To do.txt')\r\n&gt;&gt;&gt; todo.read(5)<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>&#8216;Get g&#8217;<\/p>\n<\/div>\n<p>Now when we call read() without any arguments, it reads the rest of the Python file.<\/p>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; todo.read()<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>&#8216;roceries\\nOrganize room\\nPrint labels\\nWrite article\\nStudy for examLearn to cook\\nLearn to cook&#8217;<\/p>\n<\/div>\n<p>Notice that it prints a \u2018\\n\u2019 for a newline.<\/p>\n<p>And when we yet read it, it prints an empty string, because the cursor has reached the end of the Python file.<\/p>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; todo.read()\r\n''<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">&gt;&gt; todo.close()<\/div>\n<h4>2. Seek() and tell() method in Python<\/h4>\n<p>Okay, jokes apart, these two methods let us reposition the cursor and find its position. tell() tells us where the cursor is.<\/p>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; todo=open('To do.txt')\r\n&gt;&gt;&gt; todo.read(5)<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>&#8216;Get g&#8217;<\/p>\n<\/div>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; todo.tell()<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">5<\/div>\n<p>seek() takes an integer argument, and positions the cursor after that many characters in the Python file.<\/p>\n<p>Along with that, it returns this new position of the cursor.<\/p>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; todo.seek(0)<\/pre>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; todo.read()<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">&#8216;Get groceries\\nOrganize room\\nPrint labels\\nWrite article\\nStudy for examLearn to cook\\nLearn to cook&#8217;<\/div>\n<p>seek() and tell() are like seekg(), seekp(), tellg(), and tellp() in C++.<\/p>\n<h4>3. Using Python For-loop<\/h4>\n<p>We can simply use a for-loop to iterate on a file. This is the beauty of Python- it simplifies everything.<\/p>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; for line in open('To do.txt'):\r\n           print(line,end='')<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">Get groceries<br \/>\nOrganize room<br \/>\nPrint labels<br \/>\nWrite article<br \/>\nStudy for exam<br \/>\nLearn to cook<\/div>\n<p>We used the \u2018end\u2019 parameter to prevent the interpreter from adding extra newlines to each output.<\/p>\n<p>Otherwise, the output would have looked like this:<\/p>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; for line in open('To do.txt'):\r\n         print(line)<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">Get groceries<br \/>\nOrganize room<br \/>\nPrint labels<br \/>\nWrite article<br \/>\nStudy for exam<br \/>\nLearn to cook<\/div>\n<h4>4. Readline() method in Python<\/h4>\n<p>Alternatively, the method readline() lets us read one line at a time. Simply put, the interpreter stops after every \u2018\\n\u2019.<\/p>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; todo=open('To do.txt')\r\n&gt;&gt;&gt; todo.readline()<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>&#8216;Get groceries\\n&#8217;<\/p>\n<\/div>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; todo.readline()<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>&#8216;Organize room\\n&#8217;<\/p>\n<\/div>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; todo.readline()<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>&#8216;Print labels\\n&#8217;<\/p>\n<\/div>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; todo.readline()<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>&#8216;Write article\\n&#8217;<\/p>\n<\/div>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; todo.readline()<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>&#8216;Study for exam\\n&#8217;<\/p>\n<\/div>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; todo.readline()<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>&#8216;Learn to cook&#8217;<\/p>\n<\/div>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; todo.readline()<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>&#8221;<\/p>\n<\/div>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; todo.readline()<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>&#8221;<\/p>\n<\/div>\n<h4>5. Readlines() method in Python<\/h4>\n<p>Lastly, the readlines() method reads the rest of the lines\/file.<\/p>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; todo.seek(0)<\/pre>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; todo.read(5)<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>&#8216;Get g&#8217;<\/p>\n<\/div>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; todo.readlines()<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>[&#8216;Groceries\\n&#8217;, &#8216;Organize room\\n&#8217;, &#8216;Print labels\\n&#8217;, &#8216;Write article\\n&#8217;, &#8216;Study for exam\\n&#8217;, &#8216;Learn to cook&#8217;]<\/p>\n<p>Under the hood, Python buffers reads to speed things up. Calling file.read() grabs the whole text, while file.readline() pulls one line at a time for memory-safe handling of big logs.<\/p>\n<\/div>\n<h3>Python Write to File<\/h3>\n<p>To write a Python file, we use the write() method.<\/p>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; todo=open('To do.txt')\r\n&gt;&gt;&gt; todo.write(\"HI\")<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>Traceback (most recent call last):File &#8220;&lt;pyshell#56&gt;&#8221;, line 1, in &lt;module&gt;<\/p>\n<p>todo.write(&#8220;HI&#8221;)<\/p>\n<p>io.UnsupportedOperation: not writable<\/p>\n<\/div>\n<p>Here, we did not open the Python file in a writable format. Let\u2019s open it properly.<\/p>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; todo=open('To do.txt','a')\r\n&gt;&gt;&gt; todo.write('\\nLearn to cook')<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">14<\/div>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; todo.close()<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">When we checked in the file (refreshed it), we found:Get groceries<br \/>\nOrganize room<br \/>\nPrint labels<br \/>\nWrite article<br \/>\nStudy for exam<br \/>\nLearn to cook<\/div>\n<p>Concluding, you can use \u2018w\u2019, \u2018a\u2019, or \u2018x\u2019. The \u2018w\u2019 erases the content and writes over it. So, be careful with it.<\/p>\n<p>Also, write() returned 14 here because it appended 14 characters to\u00a0Python file.<\/p>\n<p>But you can\u2019t read a Python file if you open it in \u2018a\u2019 mode.<\/p>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; todo=open('To do.txt','a')\r\n&gt;&gt;&gt; todo.read()<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>Traceback (most recent call last):File &#8220;&lt;pyshell#13&gt;&#8221;, line 1, in &lt;module&gt;<\/p>\n<p>todo.read()<\/p>\n<p>io.UnsupportedOperation: not readable<\/p>\n<\/div>\n<p>To get around this, you\u2019d have to use \u2018a+r\u2019.<\/p>\n<p>So, this was all about Python File I\/O Tutorial. Hope you like our explanation.<\/p>\n<h3>Python Interview Questions on File I\/O<\/h3>\n<p>1. What is file i\/o in Python?<\/p>\n<p>2. How to use file i\/o in Python?<\/p>\n<p>3. How does file i\/o work in Python?<\/p>\n<p>4. How do you write output to a file in Python?<\/p>\n<p>5. Why do we need files in Python?<\/p>\n<h3>Conclusion<\/h3>\n<p>In this Python file i\/o tutorial, we saw a few Python functions and methods like read(), write(), readline(), readlines(), seek(), and tell().<\/p>\n<p>Mastering these basics is your first step to building real-world applications that can save and download information.<\/p>\n<p>If you keep practicing these skills, you\u2019ll learn how they can be useful in tackling advanced tasks such as spreadsheets and databases.<\/p>\n<p>Now, you\u2019re able to manipulate files on a rudimentary level. Go ahead and practice, and come back again tomorrow for more.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>An important component of an operating system is its file and directories. We\u2019ve talked about Python Directories. In that, we learned to manipulate (create, rename, delete,..) directories. Today, we will talk about Python file&#46;&#46;&#46;<\/p>\n","protected":false},"author":5,"featured_media":8148,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[46],"tags":[4683,6447,10417,10534,10535,10537,10734,10797,10928,11362,11388,12694,14974,15296,15863],"class_list":["post-8130","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python","tag-file-in-python","tag-if-a-file-doesnt-exist","tag-python-close-file","tag-python-file","tag-python-file-io","tag-python-file-modes","tag-python-open-file","tag-python-read-files","tag-python-write-to-file","tag-read-method","tag-readlines","tag-seek-and-tell","tag-try-finally","tag-using-python-for-loop","tag-what-is-python-file"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.8 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Python File i\/o - Python Write to File and Python Read File - DataFlair<\/title>\n<meta name=\"description\" content=\"Python File i\/o-What is Python file, read file, open file, close file, write to file, readliness(), seek(), tell() etc with examples\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/data-flair.training\/blogs\/python-file\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Python File i\/o - Python Write to File and Python Read File - DataFlair\" \/>\n<meta property=\"og:description\" content=\"Python File i\/o-What is Python file, read file, open file, close file, write to file, readliness(), seek(), tell() etc with examples\" \/>\n<meta property=\"og:url\" content=\"https:\/\/data-flair.training\/blogs\/python-file\/\" \/>\n<meta property=\"og:site_name\" content=\"DataFlair\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/DataFlairWS\/\" \/>\n<meta property=\"article:published_time\" content=\"2018-02-15T03:40:36+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2026-04-22T09:41:04+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Python-Files-IO-01.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"DataFlair Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:site\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"DataFlair Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"7 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Python File i\/o - Python Write to File and Python Read File - DataFlair","description":"Python File i\/o-What is Python file, read file, open file, close file, write to file, readliness(), seek(), tell() etc with examples","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:\/\/data-flair.training\/blogs\/python-file\/","og_locale":"en_US","og_type":"article","og_title":"Python File i\/o - Python Write to File and Python Read File - DataFlair","og_description":"Python File i\/o-What is Python file, read file, open file, close file, write to file, readliness(), seek(), tell() etc with examples","og_url":"https:\/\/data-flair.training\/blogs\/python-file\/","og_site_name":"DataFlair","article_publisher":"https:\/\/www.facebook.com\/DataFlairWS\/","article_published_time":"2018-02-15T03:40:36+00:00","article_modified_time":"2026-04-22T09:41:04+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Python-Files-IO-01.jpg","type":"image\/jpeg"}],"author":"DataFlair Team","twitter_card":"summary_large_image","twitter_creator":"@DataFlairWS","twitter_site":"@DataFlairWS","twitter_misc":{"Written by":"DataFlair Team","Est. reading time":"7 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/data-flair.training\/blogs\/python-file\/#article","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/python-file\/"},"author":{"name":"DataFlair Team","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/7f83c342f5d1632d6f7b4b0b0f447823"},"headline":"Python File i\/o &#8211; Python Write to File and Python Read File","datePublished":"2018-02-15T03:40:36+00:00","dateModified":"2026-04-22T09:41:04+00:00","mainEntityOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/python-file\/"},"wordCount":1491,"commentCount":2,"publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/python-file\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Python-Files-IO-01.jpg","keywords":["File in Python","If a File Doesn\u2019t Exist","Python Close File","Python file","Python file I\/O","Python File Modes","Python Open File","Python Read files","Python Write to File","read() Method","Readlines","Seek() and tell()","Try..finally","Using Python For-loop","What is Python File"],"articleSection":["Python Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/data-flair.training\/blogs\/python-file\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/data-flair.training\/blogs\/python-file\/","url":"https:\/\/data-flair.training\/blogs\/python-file\/","name":"Python File i\/o - Python Write to File and Python Read File - DataFlair","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/#website"},"primaryImageOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/python-file\/#primaryimage"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/python-file\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Python-Files-IO-01.jpg","datePublished":"2018-02-15T03:40:36+00:00","dateModified":"2026-04-22T09:41:04+00:00","description":"Python File i\/o-What is Python file, read file, open file, close file, write to file, readliness(), seek(), tell() etc with examples","breadcrumb":{"@id":"https:\/\/data-flair.training\/blogs\/python-file\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/data-flair.training\/blogs\/python-file\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/python-file\/#primaryimage","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Python-Files-IO-01.jpg","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Python-Files-IO-01.jpg","width":1200,"height":628,"caption":"What is Python File I\/O"},{"@type":"BreadcrumbList","@id":"https:\/\/data-flair.training\/blogs\/python-file\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Blog Home","item":"https:\/\/data-flair.training\/blogs\/"},{"@type":"ListItem","position":2,"name":"Python Tutorials","item":"https:\/\/data-flair.training\/blogs\/category\/python\/"},{"@type":"ListItem","position":3,"name":"Python File i\/o &#8211; Python Write to File and Python Read File"}]},{"@type":"WebSite","@id":"https:\/\/data-flair.training\/blogs\/#website","url":"https:\/\/data-flair.training\/blogs\/","name":"DataFlair","description":"Learn Today. Lead Tomorrow.","publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/data-flair.training\/blogs\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/data-flair.training\/blogs\/#organization","name":"DataFlair","url":"https:\/\/data-flair.training\/blogs\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","width":106,"height":48,"caption":"DataFlair"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/DataFlairWS\/","https:\/\/x.com\/DataFlairWS","https:\/\/www.linkedin.com\/company\/dataflair-web-services-pvt-ltd\/","https:\/\/www.youtube.com\/user\/DataFlairWS"]},{"@type":"Person","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/7f83c342f5d1632d6f7b4b0b0f447823","name":"DataFlair Team","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/4cf3a74600d131330b8c481d519afd1574093ed89f6d3396a95393ad223eb7cd?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/4cf3a74600d131330b8c481d519afd1574093ed89f6d3396a95393ad223eb7cd?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/4cf3a74600d131330b8c481d519afd1574093ed89f6d3396a95393ad223eb7cd?s=96&d=mm&r=g","caption":"DataFlair Team"},"description":"DataFlair Team creates expert-level guides on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our goal is to empower learners with easy-to-understand content. Explore our resources for career growth and practical learning.","url":"https:\/\/data-flair.training\/blogs\/author\/dfteam1\/"}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/8130","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/comments?post=8130"}],"version-history":[{"count":15,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/8130\/revisions"}],"predecessor-version":[{"id":147767,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/8130\/revisions\/147767"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media\/8148"}],"wp:attachment":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media?parent=8130"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/categories?post=8130"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/tags?post=8130"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}