{"id":85,"date":"2026-03-01T17:30:57","date_gmt":"2026-03-01T12:30:57","guid":{"rendered":"https:\/\/gigz.pk\/python\/?post_type=lesson&#038;p=85"},"modified":"2026-03-14T08:00:35","modified_gmt":"2026-03-14T03:00:35","slug":"error-handling-in-files","status":"publish","type":"lesson","link":"https:\/\/gigz.pk\/python\/lesson\/error-handling-in-files\/","title":{"rendered":"Error Handling in Files"},"content":{"rendered":"\n<p>When working with files, errors can occur for many reasons:<\/p>\n\n\n\n<p>\u2022 File does not exist<br>\u2022 No permission to access file<br>\u2022 Disk full<br>\u2022 Wrong file mode<\/p>\n\n\n\n<p>To prevent your program from crashing, Python provides <strong>exception handling<\/strong> using <code>try<\/code> and <code>except<\/code>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>BASIC TRY-EXCEPT EXAMPLE<\/strong><\/h2>\n\n\n\n<pre class=\"wp-block-preformatted\">try:<br>    file = open(\"data.txt\", \"r\")<br>    content = file.read()<br>    print(content)<br>    file.close()<br>except:<br>    print(\"An error occurred while opening the file.\")<\/pre>\n\n\n\n<p>If an error happens, the program will not stop \u2014 it will show the error message instead.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>HANDLING SPECIFIC FILE ERRORS<\/strong><\/h2>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>1. FileNotFoundError<\/strong><\/h3>\n\n\n\n<p>Occurs when the file does not exist.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">try:<br>    with open(\"data.txt\", \"r\") as file:<br>        content = file.read()<br>except FileNotFoundError:<br>    print(\"File not found. Please check the file name.\")<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>2. PermissionError<\/strong><\/h3>\n\n\n\n<p>Occurs when you don\u2019t have permission to access the file.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">try:<br>    with open(\"data.txt\", \"w\") as file:<br>        file.write(\"Hello\")<br>except PermissionError:<br>    print(\"You do not have permission to access this file.\")<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>3. Handling Multiple Exceptions<\/strong><\/h3>\n\n\n\n<pre class=\"wp-block-preformatted\">try:<br>    with open(\"data.txt\", \"r\") as file:<br>        content = file.read()<br>except FileNotFoundError:<br>    print(\"File not found.\")<br>except PermissionError:<br>    print(\"Permission denied.\")<br>except Exception as e:<br>    print(\"Some other error occurred:\", e)<\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>USING ELSE AND FINALLY<\/strong><\/h2>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Else Block<\/strong><\/h3>\n\n\n\n<p>Runs if no error occurs.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Finally Block<\/strong><\/h3>\n\n\n\n<p>Runs no matter what (used for cleanup).<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">try:<br>    file = open(\"data.txt\", \"r\")<br>except FileNotFoundError:<br>    print(\"File not found.\")<br>else:<br>    print(file.read())<br>    file.close()<br>finally:<br>    print(\"File operation completed.\")<\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>BEST PRACTICE: WITH + TRY<\/strong><\/h2>\n\n\n\n<pre class=\"wp-block-preformatted\">try:<br>    with open(\"data.txt\", \"r\") as file:<br>        content = file.read()<br>        print(content)<br>except FileNotFoundError:<br>    print(\"File not found.\")<br>except Exception as e:<br>    print(\"Error:\", e)<\/pre>\n\n\n\n<p>Using <code>with<\/code> automatically closes the file even if an error occurs.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>WHY ERROR HANDLING IS IMPORTANT<\/strong><\/h2>\n\n\n\n<p>\u2022 Prevents program crashes<br>\u2022 Makes your program professional<br>\u2022 Helps debug problems easily<br>\u2022 Improves user experience<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>KEY TAKEAWAYS<\/strong><\/h2>\n\n\n\n<p>\u2022 Use <code>try<\/code> and <code>except<\/code> to handle file errors<br>\u2022 Handle specific exceptions when possible<br>\u2022 Use <code>with<\/code> statement for safe file handling<br>\u2022 Use <code>finally<\/code> for cleanup tasks<\/p>\n\n\n\n<p>Error handling is an essential skill for building reliable and professional Python applications.<\/p>\n\n\n<div class=\"yoast-breadcrumbs\"><span><span><a href=\"https:\/\/gigz.pk\/python\/\">Home<\/a><\/span> \u00bb <span class=\"breadcrumb_last\" aria-current=\"page\">PYTHON INTERMEDIATE (PYI) > File Handling > Error Handling in Files<\/span><\/span><\/div>\n\n\n<div class=\"schema-faq wp-block-yoast-faq-block\"><div class=\"schema-faq-section\" id=\"faq-question-1773457354555\"><strong class=\"schema-faq-question\"><\/strong> <p class=\"schema-faq-answer\"><\/p> <\/div> <\/div>\n\n\n\n<p><\/p>\n","protected":false},"menu_order":35,"template":"","class_list":["post-85","lesson","type-lesson","status-publish","hentry"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.5 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Error Handling in Files - One Language. Endless Possibilities<\/title>\n<meta name=\"description\" content=\"Learn Python file error handling using try, except, else, and finally with examples to manage FileNotFoundError and PermissionError safely.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/gigz.pk\/python\/lesson\/error-handling-in-files\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Error Handling in Files - One Language. Endless Possibilities\" \/>\n<meta property=\"og:description\" content=\"Learn Python file error handling using try, except, else, and finally with examples to manage FileNotFoundError and PermissionError safely.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/gigz.pk\/python\/lesson\/error-handling-in-files\/\" \/>\n<meta property=\"og:site_name\" content=\"One Language. Endless Possibilities\" \/>\n<meta property=\"article:modified_time\" content=\"2026-03-14T03:00:35+00:00\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data1\" content=\"1 minute\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":[\"WebPage\",\"FAQPage\"],\"@id\":\"https:\\\/\\\/gigz.pk\\\/python\\\/lesson\\\/error-handling-in-files\\\/\",\"url\":\"https:\\\/\\\/gigz.pk\\\/python\\\/lesson\\\/error-handling-in-files\\\/\",\"name\":\"Error Handling in Files - One Language. Endless Possibilities\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/gigz.pk\\\/python\\\/#website\"},\"datePublished\":\"2026-03-01T12:30:57+00:00\",\"dateModified\":\"2026-03-14T03:00:35+00:00\",\"description\":\"Learn Python file error handling using try, except, else, and finally with examples to manage FileNotFoundError and PermissionError safely.\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/gigz.pk\\\/python\\\/lesson\\\/error-handling-in-files\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/gigz.pk\\\/python\\\/lesson\\\/error-handling-in-files\\\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/gigz.pk\\\/python\\\/lesson\\\/error-handling-in-files\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/gigz.pk\\\/python\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"PYTHON INTERMEDIATE (PYI) > File Handling > Error Handling in Files\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/gigz.pk\\\/python\\\/#website\",\"url\":\"https:\\\/\\\/gigz.pk\\\/python\\\/\",\"name\":\"One Language. Endless Possibilities\",\"description\":\"\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/gigz.pk\\\/python\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Error Handling in Files - One Language. Endless Possibilities","description":"Learn Python file error handling using try, except, else, and finally with examples to manage FileNotFoundError and PermissionError safely.","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:\/\/gigz.pk\/python\/lesson\/error-handling-in-files\/","og_locale":"en_US","og_type":"article","og_title":"Error Handling in Files - One Language. Endless Possibilities","og_description":"Learn Python file error handling using try, except, else, and finally with examples to manage FileNotFoundError and PermissionError safely.","og_url":"https:\/\/gigz.pk\/python\/lesson\/error-handling-in-files\/","og_site_name":"One Language. Endless Possibilities","article_modified_time":"2026-03-14T03:00:35+00:00","twitter_card":"summary_large_image","twitter_misc":{"Est. reading time":"1 minute"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":["WebPage","FAQPage"],"@id":"https:\/\/gigz.pk\/python\/lesson\/error-handling-in-files\/","url":"https:\/\/gigz.pk\/python\/lesson\/error-handling-in-files\/","name":"Error Handling in Files - One Language. Endless Possibilities","isPartOf":{"@id":"https:\/\/gigz.pk\/python\/#website"},"datePublished":"2026-03-01T12:30:57+00:00","dateModified":"2026-03-14T03:00:35+00:00","description":"Learn Python file error handling using try, except, else, and finally with examples to manage FileNotFoundError and PermissionError safely.","breadcrumb":{"@id":"https:\/\/gigz.pk\/python\/lesson\/error-handling-in-files\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/gigz.pk\/python\/lesson\/error-handling-in-files\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/gigz.pk\/python\/lesson\/error-handling-in-files\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/gigz.pk\/python\/"},{"@type":"ListItem","position":2,"name":"PYTHON INTERMEDIATE (PYI) > File Handling > Error Handling in Files"}]},{"@type":"WebSite","@id":"https:\/\/gigz.pk\/python\/#website","url":"https:\/\/gigz.pk\/python\/","name":"One Language. Endless Possibilities","description":"","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/gigz.pk\/python\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"}]}},"_links":{"self":[{"href":"https:\/\/gigz.pk\/python\/wp-json\/wp\/v2\/lesson\/85","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/gigz.pk\/python\/wp-json\/wp\/v2\/lesson"}],"about":[{"href":"https:\/\/gigz.pk\/python\/wp-json\/wp\/v2\/types\/lesson"}],"wp:attachment":[{"href":"https:\/\/gigz.pk\/python\/wp-json\/wp\/v2\/media?parent=85"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}