{"id":24932,"date":"2023-05-08T12:52:35","date_gmt":"2023-05-08T12:52:35","guid":{"rendered":"https:\/\/www.askpython.com\/?p=24932"},"modified":"2023-05-08T12:52:36","modified_gmt":"2023-05-08T12:52:36","slug":"handling-ioerrors","status":"publish","type":"post","link":"https:\/\/www.askpython.com\/python\/examples\/handling-ioerrors","title":{"rendered":"Handling Built-in Exception IOError in Python (With Examples)"},"content":{"rendered":"\n<p>In <a href=\"https:\/\/www.askpython.com\/python\/python2-vs-python3\" target=\"_blank\" data-type=\"URL\" data-id=\"https:\/\/www.askpython.com\/python\/python2-vs-python3\" rel=\"noreferrer noopener\">Python 2<\/a>, whenever we are performing an I\/O operation and it fails, an exception is thrown called IOError.<\/p>\n\n\n\n<p>Error is an invalid code that stops the execution of the program, for instance, syntax error, logical error, type error, etc. At the same time, an exception is an error that occurs during the execution of a program and interrupts the flow of the program. IOError is also a type of exception in Python.&nbsp;<\/p>\n\n\n\n<p>In this Python tutorial, we will learn when the IOError occurs, Identify an IOError and how to handle it.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Python IOError Exception<\/h2>\n\n\n\n<p>IOError exception is raised when an input or output operation is taking place, there can be many reasons for this.<\/p>\n\n\n\n<p><strong>Below are the reasons that cause the IOError:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The file a user tried to access does not exist<\/li>\n\n\n\n<li>The user does not have permission to access the file<\/li>\n\n\n\n<li>File already in use<\/li>\n\n\n\n<li>The device is running out of space to process<\/li>\n<\/ul>\n\n\n\n<p>There may be other reasons, but these are the most commonly seen reasons.<\/p>\n\n\n\n<p><strong>Check: <a href=\"https:\/\/www.askpython.com\/python\/examples\/exceptions-in-python\" target=\"_blank\" data-type=\"URL\" data-id=\"https:\/\/www.askpython.com\/python\/examples\/exceptions-in-python\" rel=\"noreferrer noopener\">Exceptions in Python<\/a><\/strong><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Identify IOError in Python<\/h2>\n\n\n\n<p>We can identify the IOError by looking at the command line. When an IOError occurs, the Python&#8217;s interpreter throws a traceback message with the name and description of the exception.<\/p>\n\n\n\n<p>For example, if we execute the code below, see the error message we get.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nwith open(&quot;hello.py&quot;, &quot;r&quot;) as f:\n    content = f.read()\n<\/pre><\/div>\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\nTraceback (most recent call last):\n  File &quot;main.py&quot;, line 1, in &lt;module&gt;\n    with open(&quot;hello.py&quot;, &quot;r&quot;) as f:\nIOError: &#x5B;Errno 2] No such file or directory: &#039;hello.py&#039;\n<\/pre><\/div>\n\n\n<p>Here we can see that the interpreter has already mentioned IOError with a message that &#8220;No such file or directory: &#8216;hello.py'&#8221; as &#8220;hello.py&#8221; does not exist.<\/p>\n\n\n\n<p>So how do we handle this error?<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Handling IOError in Python<\/h2>\n\n\n\n<p>The IOError can be handled by using <a href=\"https:\/\/www.askpython.com\/python\/python-exception-handling\" data-type=\"URL\" data-id=\"https:\/\/www.askpython.com\/python\/python-exception-handling\" target=\"_blank\" rel=\"noreferrer noopener\">try except <\/a>block, which is the most common way for exception handling in Python. The try block contains the code that can cause an exception whereas the except clause will contain the code that executes if the IO error occurred. A try block can have more than one except clause, to specify handlers for multiple exceptions at a time.<\/p>\n\n\n\n<p><strong>Syntax:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\ntry:\n    # code that raise IOError\nexcept IOError:\n    # code to handle IOError\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">Examples of Handling IOError in Python<\/h3>\n\n\n\n<p>Let&#8217;s look at some examples of exception handling.<\/p>\n\n\n\n<p><strong>Example 1:<\/strong><\/p>\n\n\n\n<p>In this example, we will try to handle the exception when a user attempt to read a file that does not exist. We have written a print statement to display a user-friendly error message so that the user knows the reason why the file name &#8220;hello.txt&#8221; is unable to open.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\ntry:\n    with open(&quot;hello.txt&quot;, &quot;r&quot;) as f:\n        content = f.read()\nexcept IOError:\n    print(&quot;The file you are trying to access does not exist&quot;)\n<\/pre><\/div>\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\nThe file you are trying to access does not exist\n<\/pre><\/div>\n\n\n<p><strong>Example 2:<\/strong><\/p>\n\n\n\n<p>Let&#8217;s see an example of handling IOError while performing a write operation.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\ntry:\n    with open(&quot;hello.txt&quot;, &quot;r&quot;) as f:\n        f.write(&quot;Hello World!&quot;)\nexcept IOError:\n    print(&quot;The file in which you are trying to write does not exist&quot;)\n<\/pre><\/div>\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\nThe file in which you are trying to write does not exist\n<\/pre><\/div>\n\n\n<p><strong>Example 3:<\/strong><\/p>\n\n\n\n<p>Now, let&#8217;s handle the exception that occurs when the network resource we are trying to access is unavailable. Here we have also printed the actual error message.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport urllib2\n\ntry:\n\u00a0 \u00a0 response = urllib2.urlopen(&quot;http:\/\/example.com&quot;)\n\u00a0 \u00a0 html = response.read()\nexcept IOError as e:\n\u00a0 \u00a0 print(&quot;An IOError occurred: %s&quot; % e)\n<\/pre><\/div>\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\nAn IOError occurred: &lt;urlopen error &#x5B;Errno -3] Temporary failure in name resolution&gt;\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>In this tutorial, we have seen that sometimes when we are trying to read or write on a file that does not exist or the user does not have permission to access the file or the file is already in use or the device is running out of space for the operation, an IOError exception occurs.<\/p>\n\n\n\n<p>This IOError can be handled using a try-except block, just like any other exception. For handling, one can print the user-friendly message when the exception is thrown or write further code for alternate execution in the except clause. Hope now you have got enough idea about IOError and its handling in Python.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Reference<\/h2>\n\n\n\n<p><a href=\"https:\/\/docs.python.org\/3\/tutorial\/errors.html\" target=\"_blank\" rel=\"noopener\">https:\/\/docs.python.org\/3\/tutorial\/errors.html<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>In Python 2, whenever we are performing an I\/O operation and it fails, an exception is thrown called IOError. Error is an invalid code that stops the execution of the program, for instance, syntax error, logical error, type error, etc. At the same time, an exception is an error that occurs during the execution of [&hellip;]<\/p>\n","protected":false},"author":54,"featured_media":50359,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[9],"tags":[],"class_list":["post-24932","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-examples"],"blocksy_meta":[],"_links":{"self":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/24932","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/users\/54"}],"replies":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/comments?post=24932"}],"version-history":[{"count":0,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/24932\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media\/50359"}],"wp:attachment":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media?parent=24932"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/categories?post=24932"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/tags?post=24932"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}