

{"id":5809,"date":"2021-05-15T11:16:15","date_gmt":"2021-05-15T11:16:15","guid":{"rendered":"https:\/\/www.codingeek.com\/?p=5809"},"modified":"2021-05-15T11:16:17","modified_gmt":"2021-05-15T11:16:17","slug":"file-operations","status":"publish","type":"post","link":"https:\/\/www.codingeek.com\/tutorials\/python\/file-operations\/","title":{"rendered":"File operation In Python &#8211; File Handling"},"content":{"rendered":"\n<p>In this <a href=\"https:\/\/www.codingeek.com\/python-tutorials\/\" target=\"_blank\" rel=\"noreferrer noopener\">Python<\/a> article, we will discuss the complete detail of file handling in python like how to create, open, read, write, and append a file along with certain examples and bonus points. Let&#8217;s get started.<\/p>\n\n\n\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_40 counter-hierarchy ez-toc-counter ez-toc-light-blue ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\">\n<p class=\"ez-toc-title\">Table of Contents<\/p>\n<span class=\"ez-toc-title-toggle\"><a href=\"#\" class=\"ez-toc-pull-right ez-toc-btn ez-toc-btn-xs ez-toc-btn-default ez-toc-toggle\" area-label=\"ez-toc-toggle-icon-1\"><label for=\"item-6a6b1b4cb0385\" aria-label=\"Table of Content\"><span style=\"display: flex;align-items: center;width: 35px;height: 30px;justify-content: center;direction:ltr;\"><svg style=\"fill: #999;color:#999\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #999;color:#999\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/label><input  type=\"checkbox\" id=\"item-6a6b1b4cb0385\"><\/a><\/span><\/div>\n<nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/www.codingeek.com\/tutorials\/python\/file-operations\/#1_what_is_io_in_files\" title=\"1. What is I\/O in files?\">1. What is I\/O in files?<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/www.codingeek.com\/tutorials\/python\/file-operations\/#2_what_is_a_file_and_why_do_we_need_file_in_python\" title=\"2. What is a file and why do we need file in Python?\">2. What is a file and why do we need file in Python?<\/a><ul class='ez-toc-list-level-3'><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/www.codingeek.com\/tutorials\/python\/file-operations\/#21_file_object_characteristics_in_python\" title=\"2.1. File object Characteristics in Python\">2.1. File object Characteristics in Python<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/www.codingeek.com\/tutorials\/python\/file-operations\/#3_how_does_input_output_works_in_python\" title=\"3. How does Input\/ Output works in Python?\">3. How does Input\/ Output works in Python?<\/a><ul class='ez-toc-list-level-3'><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/www.codingeek.com\/tutorials\/python\/file-operations\/#31_types_of_input_from_the_keyboard\" title=\"3.1. Types of Input from the Keyboard \">3.1. Types of Input from the Keyboard <\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/www.codingeek.com\/tutorials\/python\/file-operations\/#4_what_is_file_handling_in_python\" title=\"4. What is file Handling in Python?\">4. What is file Handling in Python?<\/a><ul class='ez-toc-list-level-3'><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/www.codingeek.com\/tutorials\/python\/file-operations\/#41_different_modes_for_opening_a_file\" title=\"4.1. Different modes for opening a file\">4.1. Different modes for opening a file<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/www.codingeek.com\/tutorials\/python\/file-operations\/#5_how_to_open_a_file_in_python\" title=\" 5. How to open a file in python?\"> 5. How to open a file in python?<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-9\" href=\"https:\/\/www.codingeek.com\/tutorials\/python\/file-operations\/#6_how_to_close_files_in_python\" title=\"6. How to close files in Python?\">6. How to close files in Python?<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-10\" href=\"https:\/\/www.codingeek.com\/tutorials\/python\/file-operations\/#7_how_to_read_files_in_python\" title=\"7. How to read files in Python?\">7. How to read files in Python?<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-11\" href=\"https:\/\/www.codingeek.com\/tutorials\/python\/file-operations\/#8_how_to_write_on_a_file_using_python\" title=\"8. How to write on a file using Python?\">8. How to write on a file using Python?<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-12\" href=\"https:\/\/www.codingeek.com\/tutorials\/python\/file-operations\/#9_how_to_append_to_a_file_using_python\" title=\"9. How to append to a file using Python?\">9. How to append to a file using Python?<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-13\" href=\"https:\/\/www.codingeek.com\/tutorials\/python\/file-operations\/#10_how_can_we_rename_remove_the_file_using_python\" title=\"10. How can we rename &amp; remove the file using python?\">10. How can we rename &amp; remove the file using python?<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-14\" href=\"https:\/\/www.codingeek.com\/tutorials\/python\/file-operations\/#11_how_to_split_word_files_using_file_handling\" title=\"11. How to Split word files using file handling?\">11. How to Split word files using file handling?<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-15\" href=\"https:\/\/www.codingeek.com\/tutorials\/python\/file-operations\/#12_conclusion\" title=\"12. Conclusion\">12. Conclusion<\/a><\/li><\/ul><\/nav><\/div>\n<h2><span class=\"ez-toc-section\" id=\"1_what_is_io_in_files\"><\/span>1. What is I\/O in files?<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Input\/output operation on files includes some specific things like opening a file, read from the file, write into the file, close the file along with certain methods. Collectively it makes the I\/O in files. Now the question may arise in mind that how can we make a file in python. Hence first, let&#8217;s understand what is files.<\/p>\n\n\n\n<div class=\"wp-block-image is-style-default\"><figure class=\"aligncenter size-large is-resized\"><a href=\"https:\/\/www.codingeek.com\/wp-content\/uploads\/2021\/05\/file.png\"><img loading=\"lazy\" src=\"https:\/\/www.codingeek.com\/wp-content\/uploads\/2021\/05\/file.png\" alt=\"\" class=\"wp-image-5853\" width=\"389\" height=\"356\"\/><\/a><figcaption>File handling in Python<\/figcaption><\/figure><\/div>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2><span class=\"ez-toc-section\" id=\"2_what_is_a_file_and_why_do_we_need_file_in_python\"><\/span>2. What is a file and why do we need file in Python?<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p><strong>Any information or data which stays in the computer storage devices is known as a file<\/strong>. We already know there are different kinds of files, like music files, video files, text files etc. Python gives easy ways to manipulate these files.<\/p>\n\n\n\n<p>Generally, we divide files into two categories, <strong>text file, and binary file<\/strong>. Text files are simple text whereas binary files contain binary data which is only readable by a computer.<\/p>\n\n\n\n<p><strong>The main use of files is to store the information in any non-volatile memory<\/strong> source such as a hard disk, pen drive, SSDs, etc. <\/p>\n\n\n\n<p>While working, the data remains in the RAM which is volatile in nature meaning that data will be lost as soon as the computer turns off. Hence, there is a need for making a file to store the data permanently, whichever is needed. <\/p>\n\n\n\n<p>Before reading or writing from a file, the file must be open and after the operation is being performed, the file must be closed for the computer to release the acquired resources.<\/p>\n\n\n\n<p>Now, when we know what is files, let&#8217;s understand how python handles the files and their various operations.<\/p>\n\n\n\n<h3><span class=\"ez-toc-section\" id=\"21_file_object_characteristics_in_python\"><\/span>2.1. File object Characteristics in Python<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>After opening a file, we can use different objects related to the file which will display all information contained in the file or relevant details about the file. <\/p>\n\n\n\n<figure class=\"wp-block-table aligncenter\"><table><tbody><tr><th class=\"has-text-align-center\" data-align=\"center\">S.N.     <\/th><th class=\"has-text-align-center\" data-align=\"center\">Characteristic                 <\/th><td class=\"has-text-align-center\" data-align=\"center\"><strong>Specification<\/strong><\/td><\/tr><tr><td class=\"has-text-align-center\" data-align=\"center\">1<\/td><td class=\"has-text-align-center\" data-align=\"center\"><strong>file.closed<\/strong> <\/td><td class=\"has-text-align-center\" data-align=\"center\">If the file is closed then it will return true, otherwise false otherwise. <\/td><\/tr><tr><td class=\"has-text-align-center\" data-align=\"center\">2<\/td><td class=\"has-text-align-center\" data-align=\"center\"><strong>file.mode<\/strong><\/td><td class=\"has-text-align-center\" data-align=\"center\">It gives the access mode used to open the file.<\/td><\/tr><tr><td class=\"has-text-align-center\" data-align=\"center\">3<\/td><td class=\"has-text-align-center\" data-align=\"center\"><strong>file.name<\/strong><\/td><td class=\"has-text-align-center\" data-align=\"center\">It gives the file name<\/td><\/tr><tr><td class=\"has-text-align-center\" data-align=\"center\">4<\/td><td class=\"has-text-align-center\" data-align=\"center\"><strong>file.softspace<\/strong><\/td><td class=\"has-text-align-center\" data-align=\"center\">If explicit space is required then it will print false, otherwise true <\/td><\/tr><\/tbody><\/table><figcaption>Table for file objects<\/figcaption><\/figure>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2><span class=\"ez-toc-section\" id=\"3_how_does_input_output_works_in_python\"><\/span>3. How does Input\/ Output works in Python?<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>In python, to display the output we have the simplest command available, name as <code>print<\/code>, which has been used from the starting of the tutorial series.<\/p>\n\n\n\n<p>As we know, print takes input in brackets where we can pass variables by using commas. Print treats every <a href=\"https:\/\/www.codingeek.com\/tutorials\/python\/statements-comments-docstring-indentation\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Statements, Comments, DocString and Indentation in Python\">statement<\/a> inside it as a string and prints it as output.<\/p>\n\n\n\n<h3><span class=\"ez-toc-section\" id=\"31_types_of_input_from_the_keyboard\"><\/span>3.1. Types of Input from the Keyboard <span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>In python, we have only two <a href=\"https:\/\/www.codingeek.com\/tutorials\/python\/function\/\" title=\"User-Defined Python Functions \u2013 A complete Guide\" target=\"_blank\" rel=\"noreferrer noopener\">functions<\/a>( built-in) that help in reading lines through a standard input, which has been given using the keyboard.  These functions are \u2212<\/p>\n\n\n\n<ul><li><strong>raw_input<\/strong> &#8211; This function returns the input by reading the first line and removes all trailing next lines.<\/li><li><strong>input<\/strong> &#8211; This function is similar to the raw_input function but it estimates the input provided to be valid and returns the computed result. <\/li><\/ul>\n\n\n\n<p>However, the above difference is applicable for <strong>python 2.X<\/strong> as <strong>python 3.X only has the input function<\/strong>, it was renamed in the earlier updates.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># An example for input\nstr = input(\"Enter your input\\n\\t: \")\nprint \"Received input is : \", str<\/pre>\n\n\n\n<pre class=\"wp-block-preformatted output\"><strong>Output<\/strong>\nEnter your input\n    : dcv\nReceived input is :  dcv<\/pre>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2><span class=\"ez-toc-section\" id=\"4_what_is_file_handling_in_python\"><\/span>4. What is file Handling in Python?<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>In the development of any web application, file handling plays a vital role. Many functions come pre-installed in Python like creating a file, updating a file, reading a file, and deleting a file. <\/p>\n\n\n\n<p>In python, the primary objective of file handling is to read the files and write the files and apply certain operations on files. Many programming languages support file handling which is more or less complex and large. But python has extensive, short, and easy concepts.<\/p>\n\n\n\n<p>In python, every file is considered either as text or binary which is quite an interesting point to notice. Every code line has a character sequence which ultimately forms a file. <\/p>\n\n\n\n<p>EOL denotes that the line of the file has ended and it is terminated using a special character such as comma {,} or newline character. EOL tells the interpreter to start a new line as the existing line is terminated. <\/p>\n\n\n\n<h3><span class=\"ez-toc-section\" id=\"41_different_modes_for_opening_a_file\"><\/span>4.1. Different modes for opening a file<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>In general, python has four methods to open a file. The four different methods are:<\/p>\n\n\n\n<ul><li><code>a<\/code>\u00a0&#8211; stands for <strong>Append<\/strong> &#8211; This keyword opens the file for appending anything. If the file does not exist then it creates a new one. <\/li><li><code>r<\/code>\u00a0&#8211; stands for <strong>Read<\/strong> &#8211; This keyword opens the file for reading. If the file is not present in the system, an error will be given.<\/li><li><code>w<\/code>\u00a0&#8211; stands for <strong>Write<\/strong> &#8211; This keyword opens the file for writing. It can create a non-existing file.<\/li><li><code>x<\/code>\u00a0&#8211; stands for <strong>Create<\/strong> &#8211; This keyword is used to create the respective file. If the file is already in existence, then it will return an error.<\/li><\/ul>\n\n\n\n<p>Apart from these four methods above, we can choose whether we want to handle the file in a binary mode or text mode.<\/p>\n\n\n\n<ul><li><code>t<\/code>\u00a0&#8211; stands for <strong>Text<\/strong> &#8211; This keyword loads the default values in text format.<\/li><li><code>b<\/code>\u00a0&#8211; stands for <strong>Binary<\/strong> &#8211; This keyword loads the data in binary mode (like  loading an image)<\/li><\/ul>\n\n\n\n<pre class=\"wp-block-preformatted hit-code-sample\"><strong>Syntax<\/strong>:\nfile_1 =&nbsp;open(\"savefile.txt\",&nbsp;\"rt\")\nor\nfile_1 =&nbsp;open(\"savefile.txt\",&nbsp;\"r\")   # By default text mode<\/pre>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><th class=\"has-text-align-center\" data-align=\"center\">Modes keyword<\/th><th>Specification<\/th><\/tr><tr><td class=\"has-text-align-center\" data-align=\"center\"><code>r<\/code><\/td><td>Use to open and read a file <\/td><\/tr><tr><td class=\"has-text-align-center\" data-align=\"center\"><code>w<\/code><\/td><td>Use to open and write a file for writing. A new file will be created if it does not exist.<\/td><\/tr><tr><td class=\"has-text-align-center\" data-align=\"center\"><code>x<\/code><\/td><td>Use to open and apply exclusive creating. If the file exists, the task fails. <\/td><\/tr><tr><td class=\"has-text-align-center\" data-align=\"center\"><code>a<\/code><\/td><td>Opens a file for appending at the end of the file without truncating it. Creates a new file if it does not exist.<\/td><\/tr><tr><td class=\"has-text-align-center\" data-align=\"center\"><code>t<\/code><\/td><td>Use to open a file in text mode<\/td><\/tr><tr><td class=\"has-text-align-center\" data-align=\"center\"><code>b<\/code><\/td><td>Use to open a file in binary mode.<\/td><\/tr><tr><td class=\"has-text-align-center\" data-align=\"center\"><code>+<\/code><\/td><td>Use to open file for editing purpose<\/td><\/tr><\/tbody><\/table><figcaption>Tabular form of modes explanation <\/figcaption><\/figure>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2><span class=\"ez-toc-section\" id=\"5_how_to_open_a_file_in_python\"><\/span> 5. How to open a file in python?<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>In python, to open a file, we simply use the <code>open()<\/code> built-in\u00a0function. As soon as we call the function, an object file is assigned as an output known as a handle for modification purposes.<\/p>\n\n\n\n<p>Two arguments are passed into the open()\u00a0function which accepts the file name along with the mode of the file. Hence, the syntax becomes <strong><code>open(nameof file, modeofthefile)<\/code><\/strong>. We can also specify the buffering value. <\/p>\n\n\n\n<p><strong>Buffering<\/strong>&nbsp;\u2212 Buffering occurs when it is set to value 1 and is performed only while the file is being accessed. If the value is set to 0, buffering will not happen.<\/p>\n\n\n\n<p>We can specify the value of the buffer and the buffer will accommodate its size. If we specify a negative value, the default value will be set into the buffer. <\/p>\n\n\n\n<p><strong>Note<\/strong>: The file on which we want to perform operations can be anywhere in the system, but if the file is not in the same directory as that of the program then we have to use the fully qualified name or the relative path.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">file_1 = open('xyz.txt', 'r')\n\nfor i in file_1:    #reading line one by one\n    print (i)<\/pre>\n\n\n\n<pre class=\"wp-block-preformatted output\"><strong>Output<\/strong>\nc\nco\ncod\ncodi\ncodin\ncoding\ncodinge\ncodingee\ncodingeek\nwow! Great place reached.<\/pre>\n\n\n\n<p>The output is based on the text file data, it may vary from user to user and mode to mode.<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2><span class=\"ez-toc-section\" id=\"6_how_to_close_files_in_python\"><\/span>6. How to close files in Python?<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>After finished with the operations on the file, the file must be closed. All the resources allocated to the file will be released once we close it. We close the file with the help of &nbsp;<code>close()<\/code>&nbsp;keyword.<\/p>\n\n\n\n<p>In python, we have a garbage collector which deletes objects which are unreferenced but relying on it for closing the file is not a good decision. However, this method does not ensure full safety. If an exception occurs while performing certain operation with any file, file does not close but the code exits.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">file_1 = open('xyz.txt', 'r')\nfile_1.close() <\/pre>\n\n\n\n<p>The safest way is using try and finally block. let&#8217;s see how.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">file_1 = open('xyz.txt', 'r')\ntry:\n   file_1 = open(\"test.txt\", encoding = 'utf-8')\n   # perform file operations\nfinally:\n   file_1.close()<\/pre>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2><span class=\"ez-toc-section\" id=\"7_how_to_read_files_in_python\"><\/span>7. How to read files in Python?<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>As we discussed above, we can use the <code>r<\/code> keyword to open the file. However, there are different ways to read a file.<\/p>\n\n\n\n<p>By using we can extract a string that contains all characters in the file. Let&#8217;s take a look at a short example: <\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">file_1 = open('xyz.txt', 'r')\n\nprint (file.read(11)) #reading the 11 characters \nprint (file.read(6)) #read next 6 characters - ends with a space\nprint (file.read()) #read rest of the file\nprint (file.read()) # gives empty string<\/pre>\n\n\n\n<pre class=\"wp-block-preformatted output\"><strong>Output<\/strong>\nCodingeek -\na home \nfor developers\n<\/pre>\n\n\n\n<p>The <strong>current file cursor<\/strong> can be moved with the help of the\u00a0<code>seek()<\/code>\u00a0method and  the\u00a0<code>tell()<\/code>\u00a0method is used to return to the <strong>current position of cursor in file<\/strong>.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">file_1 = open('xyz.txt', 'r')\n\nprint(file_1.tell())    \nprint(file_1.seek(4))\nprint(file_1.tell())  <\/pre>\n\n\n\n<pre class=\"wp-block-preformatted output\"><strong>Output<\/strong>\n0\n4\n4\n<\/pre>\n\n\n\n<p>If we want the <strong>program to read lines individually<\/strong>, then we can do so with the help the\u00a0<code>readline()<\/code>\u00a0method. This enables includes the new line character while reading the file. Let&#8217;s have a look. <\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">file_1 = open('xyz.txt','r')\nprint(file_1.readline())\nprint(file_1.readline())\nprint(file_1.readline())<\/pre>\n\n\n\n<pre class=\"wp-block-preformatted output\"><strong>Output<\/strong>\nCodingeek.com\nHome for Coders\nKnowledge is power<\/pre>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2><span class=\"ez-toc-section\" id=\"8_how_to_write_on_a_file_using_python\"><\/span>8. How to write on a file using Python?<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>To write on a file, we use&nbsp;<code>write()<\/code>&nbsp;method. It writes the provided string in the mentioned file. In the string, we may pass binary data as well as the text. <\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">with open('xyz.txt', 'w', encoding = 'utf-8') as f:\n  f.write(\"Codingeek.com\\n\")\n  f.write(\"Home for Coders\")\n\nf = open('xyz.txt','r')  #checking\nprint(f.read())<\/pre>\n\n\n\n<pre class=\"wp-block-preformatted output\"><strong>Output<\/strong>\nCodingeek.com\nHome for Coders<\/pre>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2><span class=\"ez-toc-section\" id=\"9_how_to_append_to_a_file_using_python\"><\/span>9. How to append to a file using Python?<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Appending is almosst similar to writing to a fil, wehave to simply use <code>a<\/code> mode to open the file and then all the data that we write will be added to the end of the existing data.<\/p>\n\n\n\n<p>Lets assume we have a file with data &#8220;Codingeek.com&#8221; in it.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">with open('xyz.txt', 'a') as f:\n  f.write(\"\\nKnowledge is power\")\n  \nf = open('xyz.txt','r')      #checking\nprint(f.read())<\/pre>\n\n\n\n<pre class=\"wp-block-preformatted output\"><strong>Output<\/strong>\nCodingeek.com\n<strong>Knowledge is power<\/strong><\/pre>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2><span class=\"ez-toc-section\" id=\"10_how_can_we_rename_remove_the_file_using_python\"><\/span>10. How can we rename &amp; remove the file using python?<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>The python\u00a0<strong>os<\/strong>\u00a0<a href=\"https:\/\/www.codingeek.com\/tutorials\/python\/python-modules-and-import\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python Modules and how to Import Python Modules?\">module<\/a> provides methods that help you perform file-processing operations, such as renaming and deleting files.<\/p>\n\n\n\n<p>To use this module you need to import it first and then you can call any related functions.<\/p>\n\n\n\n<p>We can change the name of a file using <code>rename()<\/code> method. It accepts two arguments, the name of the current file and the name of the new file.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted hit-code-sample\"><strong>Syntax<\/strong>:\nimport os \nos.rename(r'file path\\OLD file name with ext',r'file path\\NEW file name with ext')<\/pre>\n\n\n\n<p>To remove a specific file, we use&nbsp;<code>remove()<\/code>&nbsp;method. It intakes the name of the file to be deleted as its argument.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted hit-code-sample\"><strong>Syntax<\/strong>:\nos.remove(file_name)<\/pre>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2><span class=\"ez-toc-section\" id=\"11_how_to_split_word_files_using_file_handling\"><\/span>11. How to Split word files using file handling?<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>In python, we can split each line of a file using the split method on files. It will split the variable when blank space will occur.  <\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># Python code to illustrate split() function\nwith open(\"xyz.txt\", \"r\") as f:\n  lines = f.readlines()\n  for eachline in lines:\n      char = eachline.split()\n      print (char)<\/pre>\n\n\n\n<pre class=\"wp-block-preformatted output\"><strong>Output<\/strong>\n['Codingeek.com']\n['Home', 'for', 'Coders']\n['Knowledge', 'is', 'power']<\/pre>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2><span class=\"ez-toc-section\" id=\"12_conclusion\"><\/span>12. Conclusion<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>In this article we learned about <\/p>\n\n\n\n<ul><li>What is I\/O in files in python. <\/li><li>What is a file and why do we need a file in Python along with File object characteristics<\/li><li>How does Input\/ Output work in Python and also the types of Input from the Keyboard<\/li><li>What is file Handling and Different modes for opening a file<\/li><li>How to open a file in python, close files in Python, read files in Python, and write on a file using Python?<\/li><li>How to append a file using python?<\/li><li>How can we rename &amp; remove the file using python?<\/li><li>How to Split word files using file handling?<\/li><\/ul>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<p><strong>Helpful Links<\/strong><\/p>\n\n\n\n<p>Please follow\u00a0the <strong><a href=\"https:\/\/www.codingeek.com\/python-tutorials\/\" target=\"_blank\" rel=\"noreferrer noopener\"><\/a><a href=\"https:\/\/www.codingeek.com\/python-tutorials\/\" target=\"_blank\" rel=\"noreferrer noopener\">Python tutorial series<\/a><\/strong>\u00a0or the\u00a0<strong>menu in the sidebar<\/strong>\u00a0for the complete tutorial series.<\/p>\n\n\n\n<p>Also for examples in Python and practice please refer to\u00a0<a href=\"https:\/\/www.codingeek.com\/python-examples\/\" target=\"_blank\" rel=\"noreferrer noopener\"><strong>Python Examples<\/strong><\/a>.<\/p>\n\n\n\n<p>Complete code samples are present on\u00a0<a href=\"https:\/\/github.com\/HiteshGarg\/codingeek\/tree\/master\/Python\" target=\"_blank\" rel=\"noreferrer noopener\">Github project<\/a>.<\/p>\n\n\n\n<p><strong>Recommended Books<\/strong><\/p>\n\n\n\n<a href=\"https:\/\/www.amazon.in\/dp\/0134692888?fbclid=IwAR0eDbPtsiCNSquPW3YHeJTJd3m8zHUo6PVY0EQIKNrDXFf2Z5Y_HyCB0tg&amp;linkCode=li3&amp;tag=codingeek-21&amp;linkId=7b91f6aa9d7b049597656cd5bd5817c5&amp;language=en_IN&amp;ref_=as_li_ss_il\" target=\"_blank\" rel=\"noopener\"><img border=\"0\" src=\"\/\/ws-in.amazon-adsystem.com\/widgets\/q?_encoding=UTF8&amp;ASIN=0134692888&amp;Format=_SL250_&amp;ID=AsinImage&amp;MarketPlace=IN&amp;ServiceVersion=20070822&amp;WS=1&amp;tag=codingeek-21&amp;language=en_IN\"><\/a><img loading=\"lazy\" src=\"https:\/\/ir-in.amazon-adsystem.com\/e\/ir?t=codingeek-21&amp;language=en_IN&amp;l=li3&amp;o=31&amp;a=0134692888\" width=\"1\" height=\"1\" border=\"0\" alt=\"\" style=\"border:none !important; margin:0px !important;\">\n\n<a style=\"padding-left:3px\" href=\"https:\/\/www.amazon.in\/Automate-Boring-Stuff-Python-2nd\/dp\/1593279922?pd_rd_w=HfTHM&amp;pf_rd_p=bc24ecda-5294-487e-a99f-2f95603a59d4&amp;pf_rd_r=ETWXH8FK0CG38E458SP2&amp;pd_rd_r=2626052a-2870-4319-bab0-3a3aa2223acc&amp;pd_rd_wg=jwnfU&amp;pd_rd_i=1593279922&amp;psc=1&amp;fbclid=IwAR0eDbPtsiCNSquPW3YHeJTJd3m8zHUo6PVY0EQIKNrDXFf2Z5Y_HyCB0tg&amp;linkCode=li3&amp;tag=codingeek-21&amp;linkId=ebcf34b169e248bb339c98b4ea19c821&amp;language=en_IN&amp;ref_=as_li_ss_il\" target=\"_blank\" rel=\"noopener\"><img border=\"0\" src=\"\/\/ws-in.amazon-adsystem.com\/widgets\/q?_encoding=UTF8&amp;ASIN=1593279922&amp;Format=_SL250_&amp;ID=AsinImage&amp;MarketPlace=IN&amp;ServiceVersion=20070822&amp;WS=1&amp;tag=codingeek-21&amp;language=en_IN\"><\/a><img loading=\"lazy\" src=\"https:\/\/ir-in.amazon-adsystem.com\/e\/ir?t=codingeek-21&amp;language=en_IN&amp;l=li3&amp;o=31&amp;a=1593279922\" width=\"1\" height=\"1\" border=\"0\" alt=\"\" style=\"border:none !important; margin:0px !important;\">\n\n<a style=\"padding-left:3px\" href=\"https:\/\/www.amazon.in\/Python-Crash-Course-Eric-Matthes\/dp\/1593279280?pd_rd_w=PgvgO&amp;pf_rd_p=bc24ecda-5294-487e-a99f-2f95603a59d4&amp;pf_rd_r=Z1YZ0CRKV31V2646SJFC&amp;pd_rd_r=88dac74d-ed99-4d91-801d-094fabe7ae3c&amp;pd_rd_wg=T52yH&amp;pd_rd_i=1593279280&amp;psc=1&amp;fbclid=IwAR31g6aR1FSBvqWwmoBcop-XftKLyG8Ak6jKNGUKvxohTiVQ6Gt8fSKsyUc&amp;linkCode=li3&amp;tag=codingeek-21&amp;linkId=ff7918765640a1302a16c2eed995fb20&amp;language=en_IN&amp;ref_=as_li_ss_il\" target=\"_blank\" rel=\"noopener\"><img border=\"0\" src=\"\/\/ws-in.amazon-adsystem.com\/widgets\/q?_encoding=UTF8&amp;ASIN=1593279280&amp;Format=_SL250_&amp;ID=AsinImage&amp;MarketPlace=IN&amp;ServiceVersion=20070822&amp;WS=1&amp;tag=codingeek-21&amp;language=en_IN\"><\/a><img loading=\"lazy\" src=\"https:\/\/ir-in.amazon-adsystem.com\/e\/ir?t=codingeek-21&amp;language=en_IN&amp;l=li3&amp;o=31&amp;a=1593279280\" width=\"1\" height=\"1\" border=\"0\" alt=\"\" style=\"border:none !important; margin:0px !important;\">\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<p><em><strong>An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding<\/strong><\/em><\/p>\n\n\n\n<p><em><strong>Do not forget to share and Subscribe.<\/strong><\/em><\/p>\n\n\n\n<p><em><strong>Happy coding!! <\/strong><\/em>?<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this Python article, we will discuss details of file handling in python like how to create, open, read, write, and append a file along with certain examples.<\/p>\n","protected":false},"author":22,"featured_media":5853,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[84],"tags":[86],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/www.codingeek.com\/wp-json\/wp\/v2\/posts\/5809"}],"collection":[{"href":"https:\/\/www.codingeek.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.codingeek.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.codingeek.com\/wp-json\/wp\/v2\/users\/22"}],"replies":[{"embeddable":true,"href":"https:\/\/www.codingeek.com\/wp-json\/wp\/v2\/comments?post=5809"}],"version-history":[{"count":49,"href":"https:\/\/www.codingeek.com\/wp-json\/wp\/v2\/posts\/5809\/revisions"}],"predecessor-version":[{"id":5978,"href":"https:\/\/www.codingeek.com\/wp-json\/wp\/v2\/posts\/5809\/revisions\/5978"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.codingeek.com\/wp-json\/wp\/v2\/media\/5853"}],"wp:attachment":[{"href":"https:\/\/www.codingeek.com\/wp-json\/wp\/v2\/media?parent=5809"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.codingeek.com\/wp-json\/wp\/v2\/categories?post=5809"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.codingeek.com\/wp-json\/wp\/v2\/tags?post=5809"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}