

{"id":125811,"date":"2023-11-14T19:04:34","date_gmt":"2023-11-14T13:34:34","guid":{"rendered":"https:\/\/data-flair.training\/blogs\/?p=125811"},"modified":"2024-04-23T14:57:30","modified_gmt":"2024-04-23T09:27:30","slug":"python-program-on-file-i-o","status":"publish","type":"post","link":"https:\/\/data-flair.training\/blogs\/python-program-on-file-i-o\/","title":{"rendered":"Python Program on File I\/O"},"content":{"rendered":"<p>In the vast landscape of Python programming, the ability to seamlessly read and write data in files constitutes a fundamental skill for any developer. This process not only enables the preservation and retrieval of information between program runs but also forms the backbone of various applications, from data storage to configuration management.<\/p>\n<p>Mastering Python&#8217;s File I\/O (Input\/Output) capabilities is a practical and essential aspect of programming, and in this tutorial, we&#8217;ll embark on a hands-on exploration of the methods and practices involved in reading and writing data to files, offering a comprehensive guide to enhance your proficiency in Python&#8217;s File I\/O operations.<\/p>\n<h2>Topic Explanation:<\/h2>\n<p>This tutorial explores the practical side of working with files in Python, specifically how to read and write data. We&#8217;ll start by breaking down the basics of opening files for reading and writing, helping you effectively manage the content within them.<\/p>\n<p>Our exploration will extend to methods for reading data from files, providing insights into techniques like line-by-line reading and complete file retrieval. We&#8217;ll then transition seamlessly into the art of writing data, covering diverse scenarios from creating new files to appending content to existing ones.<\/p>\n<p>As we move forward, we&#8217;ll cover more advanced file-handling techniques, including strategies to handle errors and strengthen your programs against unexpected problems. We&#8217;ll also highlight Python&#8217;s versatility by demonstrating how to deal with various types of files and gracefully manage exceptions.<\/p>\n<p>By the end of this tutorial, you&#8217;ll have a robust understanding of Python File I\/O, capable of implementing effective data reading and writing strategies in your projects.<\/p>\n<h3>Prerequisites:<\/h3>\n<ul>\n<li>Basic proficiency in Python programming, encompassing knowledge of variables, data types, and control structures.<\/li>\n<li>Familiarity with file system concepts, including directories, file paths, and file permissions.<\/li>\n<li>A functional Python interpreter installed on your machine.<\/li>\n<li>Prior exposure to basic file handling operations (optional but beneficial).<\/li>\n<\/ul>\n<h3>Code 1 with comments:<\/h3>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\"># Use a try-except block to handle potential exceptions\r\ntry:\r\n    # Open the file in \"a\" (append) mode, creating the file if it doesn't exist\r\n    f = open(\"c:\/\/myfile\/employee.txt\", \"a\")\r\n\r\n    # Prompt the user to enter a string for the file\r\n    str_input = input(\"Enter a String for file: \")\r\n\r\n    # Write the entered string to the file\r\n    f.write(str_input)\r\n\r\n    # Display the close status of the file before closing\r\n    print(\"Close status before closing\")\r\n    print(f.closed)\r\n\r\n    # Close the file\r\n    f.close()\r\n\r\n    # Display the close status of the file after closing\r\n    print(\"Close status after closing\")\r\n    print(f.closed)\r\n\r\n# Catch the FileNotFoundError exception and print the corresponding error message\r\nexcept FileNotFoundError as obj:\r\n    print(obj)<\/pre>\n<p><strong>Output for code 1:<\/strong><br \/>\nEnter a String for file: Hello, this is a test string!<br \/>\nClose status before closing<br \/>\nFalse<br \/>\nClose status after closing<br \/>\nTrue<\/p>\n<h4>Code 1 Explanation:<\/h4>\n<ul>\n<li><strong>try::<\/strong> Begins a block where potential exceptions might occur.<\/li>\n<li><strong>f = open(&#8220;c:\/\/myfile\/employee.txt&#8221;, &#8220;a&#8221;):<\/strong> Opens the file &#8220;employee.txt&#8221; in append mode (&#8220;a&#8221;). If the file doesn&#8217;t exist, it will be created. The file object is stored in the variable f.<br \/>\n<strong>str_input = input(&#8220;Enter a String for file: &#8220;):<\/strong> Prompts the user to enter a string for the file and stores it in the variable str_input.<\/li>\n<li><strong>f.write(str_input):<\/strong> Writes the entered string to the file.<\/li>\n<li><strong>print(&#8220;Close status before closing&#8221;):<\/strong> Displays a message indicating that the next line will show the close status before closing.<\/li>\n<li><strong>print(f.closed):<\/strong> Prints the close status of the file before closing (should be False).<\/li>\n<li><strong>f.close():<\/strong> Closes the file.<\/li>\n<li><strong>print(&#8220;Close status after closing&#8221;):<\/strong> Displays a message indicating that the next line will show the close status after closing.<\/li>\n<li><strong>print(f.closed):<\/strong> Prints the close status of the file after closing (should be True if closed successfully).<\/li>\n<li><strong>except FileNotFoundError as obj::<\/strong> Catches the FileNotFoundError exception, if it occurs, and stores the exception object in the variable obj.<\/li>\n<li><strong>print(obj):<\/strong> Prints the error message associated with the FileNotFoundError.<\/li>\n<\/ul>\n<h3>Code 2 with comments:<\/h3>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\"># Use a try-except block to handle potential exceptions\r\ntry:\r\n    # Open the file in \"a\" (append) mode, creating the file if it doesn't exist\r\n    f = open(\"c:\/\/myfile\/employee.txt\", \"a\")\r\n\r\n    # Create a list containing strings to be written to the file\r\n    mylist = [\"This is a class\\n Data Flair Python Course\\n Data flair Free Course\"]\r\n\r\n    # Write the list of strings to the file\r\n    f.writelines(mylist)\r\n\r\n    # Close the file\r\n    f.close()\r\n\r\n    # Print a message indicating that the file is created\r\n    print(\"File created.....\")\r\n\r\n# Catch the FileNotFoundError exception and print a corresponding error message\r\nexcept FileNotFoundError as obj:\r\n    print(\"File Not found....\")<\/pre>\n<p><strong>Output for code 2:<\/strong><br \/>\nFile created&#8230;..<\/p>\n<h4>Code 2 Explanation:<\/h4>\n<ul>\n<li><strong>try::<\/strong> Begins a block where potential exceptions might occur.<\/li>\n<li><strong>f = open(&#8220;c:\/\/myfile\/employee.txt&#8221;, &#8220;a&#8221;):<\/strong> Opens the file &#8220;employee.txt&#8221; in append mode (&#8220;a&#8221;). If the file doesn&#8217;t exist, it will be created. The file object is stored in the variable f.<\/li>\n<li><strong>mylist = [&#8220;This is a class\\n Data Flair Python Course\\n Data flair Free Course&#8221;]:<\/strong> Creates a list containing strings to be written to the file. Note that the list contains a single string with newline characters.<\/li>\n<li><strong>f.writelines(mylist):<\/strong> Writes the list of strings to the file. Each string in the list will be written on a new line in the file due to the newline characters.<\/li>\n<li><strong>f.close():<\/strong> Closes the file.<\/li>\n<li><strong>print(&#8220;File created&#8230;..&#8221;):<\/strong> Prints a message indicating that the file is created.<\/li>\n<\/ul>\n<h3>Code 3 with Comments:<\/h3>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\"># Import the os and sys modules for operating system-related functionalities and system-specific parameters\r\nimport os\r\nimport sys\r\n\r\n# Prompt the user to enter a file name for reading data\r\nstr_input = input(\"Enter file name for read data\")\r\n\r\n# Use a try-except block to handle potential exceptions\r\ntry:\r\n    # Check if the file exists in the specified path\r\n    if os.path.isfile(\"c:\/\/myfile\/\" + str_input + \".txt\"):\r\n        \r\n        # Open the file in read mode\r\n        f = open(\"c:\/\/myfile\/\" + str_input + \".txt\", \"r\")\r\n        \r\n        # Check if the file is readable\r\n        if f.readable():\r\n            # Initialize variables to count lines, words, and characters\r\n            cl = cw = cc = 0\r\n            \r\n            # Read the entire content of the file\r\n            str_data = f.read()\r\n            \r\n            # Print the content of the file\r\n            print(str_data)\r\n    \r\n    else:\r\n        # Print a message if the file does not exist and exit the program\r\n        print(\"File not exists\")\r\n        sys.exit()\r\n\r\n# Catch the FileNotFoundError exception and print the corresponding error message\r\nexcept FileNotFoundError as msg:\r\n    print(msg)<\/pre>\n<p><strong>Output For code 3:<\/strong><\/p>\n<p>The output of the provided code depends on the user input and the existence of the specified file. Here are a few possible scenarios:<\/p>\n<p><strong>1. File Exists and Readable:<\/strong><br \/>\n<strong>Enter file name for read data:<\/strong> example<br \/>\nThis is the content of the example.txt file.<br \/>\n<strong>2.File Does Not Exi<\/strong>st:<br \/>\n<strong>Enter file name for read data:<\/strong> non_existent_file<br \/>\nFile not exists<br \/>\n<strong>3.File Exists but Not Readable:<\/strong><br \/>\n<strong>Enter file name for read data:<\/strong> unreadable_file<br \/>\n[Content of the file is not printed]<br \/>\nIn this case, the program won&#8217;t print the content of the file because it is not readable.<br \/>\n<strong>4.File Not Found (Error):<\/strong><br \/>\n<strong>Enter file name for read data:<\/strong> invalid_file<br \/>\n[FileNotFoundError message is printed].<\/p>\n<h4>Code 3 Explanation:<\/h4>\n<p><strong>1. import os:<\/strong> Imports the os module, which provides a way to interact with the operating system.<br \/>\n<strong>2. import sys:<\/strong> Imports the sys module, which provides access to some variables used or maintained by the Python interpreter.<br \/>\n<strong>3. str_input = input(&#8220;Enter file name for read data&#8221;):<\/strong> Prompts the user to enter a file name for reading data and stores it in the variable str_input.<br \/>\n<strong>4. try::<\/strong> Begins a block where potential exceptions might occur.<br \/>\n<strong>5. if os.path.isfile(&#8220;c:\/\/myfile\/&#8221; + str_input + &#8220;.txt&#8221;)::<\/strong> Checks if the file exists in the specified path using os.path.isfile.<br \/>\n<strong>6. f = open(&#8220;c:\/\/myfile\/&#8221; + str_input + &#8220;.txt&#8221;, &#8220;r&#8221;):<\/strong> Opens the file in read mode (&#8220;r&#8221;) and stores the file object in the variable f.<br \/>\n<strong>7. if f.readable()::<\/strong> Checks if the file is readable.<br \/>\n<strong>8. cl = cw = cc = 0:<\/strong> Initializes variables to count lines (cl), words (cw), and characters (cc).<br \/>\n<strong>9. str_data = f.read():<\/strong> Reads the entire content of the file and stores it in the variable str_data.<br \/>\n<strong>10. print(str_data):<\/strong> Prints the content of the file.<br \/>\n<strong>11. else::<\/strong> Executes if the file does not exist.<\/p>\n<ul>\n<li>print(&#8220;File not exists&#8221;): Prints a message indicating that the file does not exist.<\/li>\n<li>sys.exit(): Exits the program.<\/li>\n<\/ul>\n<p><strong>12. except FileNotFoundError as msg::<\/strong> Catches the FileNotFoundError exception, if it occurs, and prints the corresponding error message.<\/p>\n<h3>Conclusion:<\/h3>\n<p>In the expansive domain of Python programming, this proficiency facilitates the persistence and retrieval of information across program executions, serving as a critical backbone for a myriad of applications, from data storage to configuration management.<\/p>\n<p>Python&#8217;s File I\/O capabilities, explored in this tutorial, constitute a practical and indispensable dimension of programming expertise. As the tutorial progresses, emphasis is placed on advanced file handling practices, incorporating error-handling strategies to fortify programs against unforeseen issues. This tutorial highlights Python&#8217;s versatile capabilities, showcasing how to navigate different file types and gracefully handle exceptions.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In the vast landscape of Python programming, the ability to seamlessly read and write data in files constitutes a fundamental skill for any developer. This process not only enables the preservation and retrieval of&#46;&#46;&#46;<\/p>\n","protected":false},"author":581,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[46],"tags":[10333,10535,28626,28911,28912],"class_list":["post-125811","post","type-post","status-publish","format-standard","hentry","category-python","tag-python","tag-python-file-io","tag-python-practical","tag-python-program-on-file-i-o","tag-read-and-write-data-in-files"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.8 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Python Program on File I\/O - DataFlair<\/title>\n<meta name=\"description\" content=\"This Python tutorial explores the practical side of working with files in Python, specifically how to read and write data.\" \/>\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-program-on-file-i-o\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Python Program on File I\/O - DataFlair\" \/>\n<meta property=\"og:description\" content=\"This Python tutorial explores the practical side of working with files in Python, specifically how to read and write data.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/data-flair.training\/blogs\/python-program-on-file-i-o\/\" \/>\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=\"2023-11-14T13:34:34+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-04-23T09:27:30+00:00\" \/>\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=\"5 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Python Program on File I\/O - DataFlair","description":"This Python tutorial explores the practical side of working with files in Python, specifically how to read and write data.","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-program-on-file-i-o\/","og_locale":"en_US","og_type":"article","og_title":"Python Program on File I\/O - DataFlair","og_description":"This Python tutorial explores the practical side of working with files in Python, specifically how to read and write data.","og_url":"https:\/\/data-flair.training\/blogs\/python-program-on-file-i-o\/","og_site_name":"DataFlair","article_publisher":"https:\/\/www.facebook.com\/DataFlairWS\/","article_published_time":"2023-11-14T13:34:34+00:00","article_modified_time":"2024-04-23T09:27:30+00:00","author":"DataFlair Team","twitter_card":"summary_large_image","twitter_creator":"@DataFlairWS","twitter_site":"@DataFlairWS","twitter_misc":{"Written by":"DataFlair Team","Est. reading time":"5 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/data-flair.training\/blogs\/python-program-on-file-i-o\/#article","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/python-program-on-file-i-o\/"},"author":{"name":"DataFlair Team","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/c187795dc82ab948373cca526df7c445"},"headline":"Python Program on File I\/O","datePublished":"2023-11-14T13:34:34+00:00","dateModified":"2024-04-23T09:27:30+00:00","mainEntityOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/python-program-on-file-i-o\/"},"wordCount":1108,"commentCount":0,"publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"keywords":["Python","Python file I\/O","python practical","python program on file i\/o","read and write data in files"],"articleSection":["Python Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/data-flair.training\/blogs\/python-program-on-file-i-o\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/data-flair.training\/blogs\/python-program-on-file-i-o\/","url":"https:\/\/data-flair.training\/blogs\/python-program-on-file-i-o\/","name":"Python Program on File I\/O - DataFlair","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/#website"},"datePublished":"2023-11-14T13:34:34+00:00","dateModified":"2024-04-23T09:27:30+00:00","description":"This Python tutorial explores the practical side of working with files in Python, specifically how to read and write data.","breadcrumb":{"@id":"https:\/\/data-flair.training\/blogs\/python-program-on-file-i-o\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/data-flair.training\/blogs\/python-program-on-file-i-o\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/data-flair.training\/blogs\/python-program-on-file-i-o\/#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 Program on File I\/O"}]},{"@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\/c187795dc82ab948373cca526df7c445","name":"DataFlair Team","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/2302ebc438084d2f1f993edc1996a0aae01332e81f3227cba8df0c48ec010ca4?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/2302ebc438084d2f1f993edc1996a0aae01332e81f3227cba8df0c48ec010ca4?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/2302ebc438084d2f1f993edc1996a0aae01332e81f3227cba8df0c48ec010ca4?s=96&d=mm&r=g","caption":"DataFlair Team"},"description":"DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.","url":"https:\/\/data-flair.training\/blogs\/author\/dfteam6\/"}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/125811","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\/581"}],"replies":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/comments?post=125811"}],"version-history":[{"count":3,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/125811\/revisions"}],"predecessor-version":[{"id":136399,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/125811\/revisions\/136399"}],"wp:attachment":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media?parent=125811"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/categories?post=125811"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/tags?post=125811"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}