{"id":21494,"date":"2022-12-19T06:56:00","date_gmt":"2022-12-19T05:56:00","guid":{"rendered":"https:\/\/expert-only.com\/?p=21494"},"modified":"2023-01-18T10:24:50","modified_gmt":"2023-01-18T09:24:50","slug":"text-files-in-python","status":"publish","type":"post","link":"https:\/\/expert-only.com\/en\/python\/text-files-in-python\/","title":{"rendered":"Manage text files in Python using read and write methods"},"content":{"rendered":"\n<h4 class=\"has-text-align-center wp-block-heading\" id=\"h-python-tutorial-on-how-to-manage-text-files-using-the-open-read-readline-write-writelines-seek-and-close-methods-with-scripts-examples\"><strong><em>Python tutorial on how to manage text files using the open, read, readline, write, writelines, seek and close methods with scripts examples.<\/em><\/strong><\/h4>\n\n\n\n<p>This tutorial on how to manage text files in Python provide some information and code examples on working with files using Python scripts. Text files are a fundamental part of computer science and are used to store plain text data. They are widely used in various applications, such as storing configuration files, logs, and data for machine learning models. <a href=\"https:\/\/expert-only.com\/en\/learn-python-programming\/\">Python programming<\/a> allows to easily read, write, append and manipulate lines using the built-in functions and modules.<\/p>\n\n\n\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_82_2 ez-toc-wrap-center counter-hierarchy ez-toc-counter ez-toc-grey ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<span class=\"ez-toc-title-toggle\"><\/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:\/\/expert-only.com\/en\/python\/text-files-in-python\/#1-file-opening-modes-in-python\" >1. File opening modes in Python<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/expert-only.com\/en\/python\/text-files-in-python\/#2-how-to-manage-text-files-with-basic-python-operations\" >2. How to manage text files with basic Python operations?<\/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:\/\/expert-only.com\/en\/python\/text-files-in-python\/#21-opening-a-text-file-in-python\" >2.1 Opening a text file in Python<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/expert-only.com\/en\/python\/text-files-in-python\/#22-read-a-text-file-in-python\" >2.2 Read a text file in Python<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/expert-only.com\/en\/python\/text-files-in-python\/#23-write-to-a-text-file-in-python\" >2.3 Write to a text file in Python<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/expert-only.com\/en\/python\/text-files-in-python\/#24-close-a-text-file-using-python\" >2.4 Close a text file using Python<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/expert-only.com\/en\/python\/text-files-in-python\/#3-read-text-files-with-python\" >3. Read text files with Python<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/expert-only.com\/en\/python\/text-files-in-python\/#31-open-and-read-a-text-file-in-python\" >3.1 Open and read a text file in Python<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-9\" href=\"https:\/\/expert-only.com\/en\/python\/text-files-in-python\/#32-read-a-specific-number-of-characters-or-lines\" >3.2 Read a specific number of characters or lines<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-10\" href=\"https:\/\/expert-only.com\/en\/python\/text-files-in-python\/#33-iterate-over-the-lines-of-a-text-file-in-python\" >3.3 Iterate over the lines of a text file in Python<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-11\" href=\"https:\/\/expert-only.com\/en\/python\/text-files-in-python\/#34-read-a-file-line-by-line-and-store-it-in-a-list-with-python\" >3.4 Read a file line by line and store it in a list with Python<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-12\" href=\"https:\/\/expert-only.com\/en\/python\/text-files-in-python\/#4-write-text-files-with-python-scripts\" >4. Write text files with Python scripts<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-13\" href=\"https:\/\/expert-only.com\/en\/python\/text-files-in-python\/#41-open-and-write-to-a-text-file-in-python\" >4.1 Open and write to a text file in Python<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-14\" href=\"https:\/\/expert-only.com\/en\/python\/text-files-in-python\/#42-write-to-a-specific-position-in-a-text-file\" >4.2 Write to a specific position in a text file<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-15\" href=\"https:\/\/expert-only.com\/en\/python\/text-files-in-python\/#43-append-text-to-a-file-with-python\" >4.3 Append text to a file with Python<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-16\" href=\"https:\/\/expert-only.com\/en\/python\/text-files-in-python\/#44-write-to-a-file-line-by-line\" >4.4 Write to a file line by line<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-17\" href=\"https:\/\/expert-only.com\/en\/python\/text-files-in-python\/#5-manipulate-data-in-text-files-using-python\" >5. Manipulate data in text files using Python<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-18\" href=\"https:\/\/expert-only.com\/en\/python\/text-files-in-python\/#51-search-for-a-specific-string-using-the-find-method\" >5.1 Search for a specific string using the find method<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-19\" href=\"https:\/\/expert-only.com\/en\/python\/text-files-in-python\/#52-search-specific-strings-using-search-method\" >5.2 Search specific strings using search method<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-20\" href=\"https:\/\/expert-only.com\/en\/python\/text-files-in-python\/#53-search-for-a-specific-string-with-python\" >5.3 Search for a specific string with Python<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-21\" href=\"https:\/\/expert-only.com\/en\/python\/text-files-in-python\/#54-search-patterns-with-findall-and-finditer\" >5.4 Search patterns with findall and finditer<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-22\" href=\"https:\/\/expert-only.com\/en\/python\/text-files-in-python\/#55-replace-a-text-in-a-file-in-python\" >5.5 Replace a text in a file in Python<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-23\" href=\"https:\/\/expert-only.com\/en\/python\/text-files-in-python\/#56-python-script-to-sort-lines-of-a-file\" >5.6 Python script to sort lines of a file<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-24\" href=\"https:\/\/expert-only.com\/en\/python\/text-files-in-python\/#57-extract-specific-lines-from-a-txt-file\" >5.7 Extract specific lines from a txt file<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-25\" href=\"https:\/\/expert-only.com\/en\/python\/text-files-in-python\/#conclusion-on-managing-text-files-in-python\" >Conclusion on managing text files in Python<\/a><\/li><\/ul><\/nav><\/div>\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"1-file-opening-modes-in-python\"><\/span>1. File opening modes in Python<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>In order to manage text files using Python scripts, you must know the file access modes and their specificities. The <strong>file access modes<\/strong> in Python are used to determine the type of operations that can be performed on files after opening them. These modes also determine the location of the Python reading method, it is like a cursor, called <strong><em>file handle<\/em><\/strong>.  It is important because it defines the position of reading and writing, physically in the file system.<\/p>\n\n\n\n<p>There are <strong>six different file access modes in Pytho<\/strong>n that are used to open and manipulate files.<\/p>\n\n\n\n<figure class=\"wp-block-table aligncenter is-style-stripes\"><table><thead><tr><th class=\"has-text-align-center\" data-align=\"center\">#<\/th><th class=\"has-text-align-center\" data-align=\"center\">File opening mode name<\/th><th class=\"has-text-align-center\" data-align=\"center\">Syntax<\/th><\/tr><\/thead><tbody><tr><td class=\"has-text-align-center\" data-align=\"center\">1<\/td><td class=\"has-text-align-center\" data-align=\"center\">Read only mode<\/td><td class=\"has-text-align-center\" data-align=\"center\"><strong>r<\/strong><\/td><\/tr><tr><td class=\"has-text-align-center\" data-align=\"center\">2<\/td><td class=\"has-text-align-center\" data-align=\"center\">Read and write only mode<\/td><td class=\"has-text-align-center\" data-align=\"center\"><strong>r+<\/strong><\/td><\/tr><tr><td class=\"has-text-align-center\" data-align=\"center\">3<\/td><td class=\"has-text-align-center\" data-align=\"center\">Write only mode<\/td><td class=\"has-text-align-center\" data-align=\"center\"><strong>w<\/strong><\/td><\/tr><tr><td class=\"has-text-align-center\" data-align=\"center\">4<\/td><td class=\"has-text-align-center\" data-align=\"center\">Write and read<\/td><td class=\"has-text-align-center\" data-align=\"center\"><strong>w+<\/strong><\/td><\/tr><tr><td class=\"has-text-align-center\" data-align=\"center\">5<\/td><td class=\"has-text-align-center\" data-align=\"center\">Append only<\/td><td class=\"has-text-align-center\" data-align=\"center\"><strong>a<\/strong><\/td><\/tr><tr><td class=\"has-text-align-center\" data-align=\"center\">6<\/td><td class=\"has-text-align-center\" data-align=\"center\">Append and read<\/td><td class=\"has-text-align-center\" data-align=\"center\"><strong>a+<\/strong><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h4 class=\"wp-block-heading\">1. Read only mode: r<\/h4>\n\n\n\n<p>When working with files with Python scripts, the <strong>read only mode<\/strong>, or r mode is useful to open a text file for reading only. This means that the file can be read, but not written to. When a file is opened in this mode, the file pointer is set at the start of the file. In case the file specified does not exist, it will result in an input\/output error. <strong>The read only mode is the default mode<\/strong> in which a file is opened in absence of any specified mode.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">2. Read and write only mode: r+<\/h4>\n\n\n\n<p>The read and write mode, also called the <strong>r+<\/strong> mode in Python file handling is used to open a file for both reading and writing operations. This means that once the file is opened in this mode, you can read from it as well as write to it.<\/p>\n\n\n\n<p>The file pointer is positioned at the start of the file, so you can begin reading or writing from the very beginning. However, if the specified file does not exist, it will result in an <strong>Input\/Output error<\/strong> (also called I\/O error), as no operations can be performed. This mode is useful when you want to both read from and write to a file, while keeping the file pointer at the beginning of the file.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">3. Write only mode: w<\/h4>\n\n\n\n<p>The w mode, also called the write only mode in Python file management is used to open a file <strong>exclusively for writing operations<\/strong>. This means that once the file is opened in this mode, you can write to it, but not read from it. If the file already exists, all the <strong>data in the file is truncated and overwritten<\/strong>. In this mode, the file pointer is also positioned at the beginning of the file.<\/p>\n\n\n\n<p>In case the specified file does not exist, a new file will be created with the same name. This mode is useful when you want to create a new file or overwrite an existing file. It is important to note that, it&#8217;s a dangerous mode to use as it may lose the data if the file already exists, so it&#8217;s good to have a backup before using it. It also special because you cannot check the content of files before writing.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">4. Write and read mode: w+<\/h4>\n\n\n\n<p>The <strong>Python w+ mode<\/strong> is used to open a file for both reading and writing operations. This means that once the file is opened in this mode, you can read from it as well as write to it. <\/p>\n\n\n\n<p>However, if the file already exists, all the data in the file will be truncated and overwritten. Indeed, any existing content in the file will be deleted and replaced with the new data. Also, if the specified file does not exist, a new file will be created with the same name. This mode is useful when you want to create a new file or overwrite an existing one while being able also to read it afterwards.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">5. Append only mode: a<\/h4>\n\n\n\n<p>The append mode in Python, is used to open a file exclusively for writing operations, but with a specific feature, the <strong>file handle is positioned at the end of the file<\/strong>. Technically, it means that any data written to the file will be appended to the end of the existing data.<\/p>\n\n\n\n<p>If the specified file does not exist, a new file will is created with the name provided. This mode is very useful to add new data to an existing file without overwriting any of the existing data. It&#8217;s worth noting that, the file is created if it does not exist, so it&#8217;s a safe option to use when you want to add new data to a file without losing the existing one. This mode is particularly <strong>useful with log files<\/strong>, to keep track of new events without erasing previous records.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">6. Append and read mode: a+<\/h4>\n\n\n\n<p>The append and read mode in Python, is useful to open a file for read and also write operations. It simply the read option the append only mode. Like in the previous mode wee saw, with the <strong>a+ mode<\/strong>, the file handle is positioned at the end of the file, i.e., the data written is inserted after the existing data. <\/p>\n\n\n\n<p>This mode is useful when you want to append new data to an existing file, while still being able to read the contents of the file afterwards, for example, to read the last line written in the file. Also in this mode, any existing data in the file is not overwritten, only new data is added at the end of the file.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-2-how-to-manage-text-files-with-basic-python-operations\"><span class=\"ez-toc-section\" id=\"2-how-to-manage-text-files-with-basic-python-operations\"><\/span>2. How to manage text files with basic Python operations?<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>In Python, working with text files involves opening the file, performing operations on it, and closing the file. Here are some basic operations that can be performed on text files in Python using the <strong>open<\/strong>, <strong>read<\/strong>, <strong>write<\/strong> and <strong>close<\/strong> methods.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-2-1-opening-a-text-file-in-python\"><span class=\"ez-toc-section\" id=\"21-opening-a-text-file-in-python\"><\/span>2.1 Opening a text file in Python<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>To open a text file in Python, we use the built-in <code>open()<\/code> function. The function takes the file name and the mode in which the file should be opened (e.g. &#8216;r&#8217; for reading, &#8216;w&#8217; for writing, &#8216;a&#8217; for appending, etc.) as arguments. Here is a first example of how to <strong>open a text file in read-only mode<\/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 = open('example.txt', 'r')\n<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-2-2-read-a-text-file-in-python\"><span class=\"ez-toc-section\" id=\"22-read-a-text-file-in-python\"><\/span>2.2 Read a text file in Python<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>Once a file is opened, it can be read using the <code>read()<\/code> method. This method takes an optional argument that specifies the number of characters to be read. If no argument is passed, the entire file is read. Here is a second example, this time on how to read the entire contents of a file.<\/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=\"\">content = file.read()\nprint(content)\n<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-2-3-write-to-a-text-file-in-python\"><span class=\"ez-toc-section\" id=\"23-write-to-a-text-file-in-python\"><\/span>2.3 Write to a text file in Python<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>To write to a text file, it must be opened in write mode (&#8216;w&#8217;). The <code>write()<\/code> method is used to write data to the file. Here is the third example of the section, with a script to write a string to a text file.<\/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 = open('example.txt', 'w')\nfile.write('Hello World')\n<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-2-4-close-a-text-file-using-python\"><span class=\"ez-toc-section\" id=\"24-close-a-text-file-using-python\"><\/span>2.4 Close a text file using Python<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>It is important to close a file after performing operations on it to ensure that the changes are saved and to release the resources used by the file. The <code>close()<\/code> method is used to close a file.<\/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.close()\n<\/pre>\n\n\n\n<p>It&#8217;s important to note that when you open a file in write mode, the existing content of the file is truncated, so the data in the file is deleted, and new data is written. To go further on Python programming concepts, the best way to manage lines from files is to use <a href=\"https:\/\/expert-only.com\/en\/python\/python-lists\/\">the Python lists data type<\/a>.<\/p>\n\n\n\n<figure class=\"wp-block-embed is-type-wp-embed is-provider-sql-and-it-tutorials wp-block-embed-sql-and-it-tutorials\"><div class=\"wp-block-embed__wrapper\">\n<blockquote class=\"wp-embedded-content\" data-secret=\"olIEVmR93d\"><a href=\"https:\/\/expert-only.com\/en\/python\/python-lists\/\">Python lists<\/a><\/blockquote><iframe loading=\"lazy\" class=\"wp-embedded-content\" sandbox=\"allow-scripts\" security=\"restricted\" style=\"position: absolute; clip: rect(1px, 1px, 1px, 1px);\" title=\"&#8220;Python lists&#8221; &#8212; SQL and IT Tutorials\" src=\"https:\/\/expert-only.com\/en\/python\/python-lists\/embed\/#?secret=WE3fWf45iQ#?secret=olIEVmR93d\" data-secret=\"olIEVmR93d\" width=\"500\" height=\"282\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"no\"><\/iframe>\n<\/div><\/figure>\n\n\n\n<p>In the next sections, we will cover more <strong>advanced Python operations with text files<\/strong> such as reading and writing in specific positions, appending, and manipulating the content of text files.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-3-read-text-files-with-python\"><span class=\"ez-toc-section\" id=\"3-read-text-files-with-python\"><\/span>3. Read text files with Python<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>In this second section about how to manage files in Python, we will delve deeper into reading text files in Python. We will cover different techniques for opening and reading text files, including reading a specific number of characters or lines, iterating over the lines of a text file, and storing the contents of a text file in a list or other data structure. We will also provide examples and code snippets to demonstrate each technique in action.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-3-1-open-and-read-a-text-file-in-python\"><span class=\"ez-toc-section\" id=\"31-open-and-read-a-text-file-in-python\"><\/span>3.1 Open and read a text file in Python<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>As mentioned in the introduction, the <code>open()<\/code> function is used to open a text file in Python. To read a text file, it should be opened in read mode (&#8216;r&#8217;). Once the file is open, the entire contents of the file can be read using the <code>read()<\/code> method. Here is an example of how to open a text file, again in read only mode and read its contents, using 4 lines of scripts.<\/p>\n\n\n\n<p>In this example, the script reads the file located in <strong>C:\\data\\example.txt<\/strong> in read only mode and display the full content, i.e., 21 lines of data. The file includes 1 <strong>header<\/strong> line and 20 lines of <strong>data<\/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 = open('C:\\data\\example.txt', 'r')\ncontent = file.read()\nprint(content)\nfile.close()\n<\/pre>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"720\" height=\"680\" src=\"https:\/\/expert-only.com\/wp-content\/uploads\/2023\/01\/python-text-files-read-txt-content.jpg\" alt=\"Use the open and read methods to manage text files in Python\" class=\"wp-image-21545\" srcset=\"https:\/\/expert-only.com\/wp-content\/uploads\/2023\/01\/python-text-files-read-txt-content.jpg 720w, https:\/\/expert-only.com\/wp-content\/uploads\/2023\/01\/python-text-files-read-txt-content-300x283.jpg 300w\" sizes=\"auto, (max-width: 720px) 100vw, 720px\" \/><figcaption class=\"wp-element-caption\"><strong>Use the open and read methods to manage text files in Python<\/strong><\/figcaption><\/figure><\/div>\n\n\n<h3 class=\"wp-block-heading\" id=\"h-3-2-read-a-specific-number-of-characters-or-lines\"><span class=\"ez-toc-section\" id=\"32-read-a-specific-number-of-characters-or-lines\"><\/span>3.2 Read a specific number of characters or lines<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>This second example of the section on reading text files using Python is a little bit more advanced. Indeed, sometimes, we only need to read a specific number of characters or lines from a text file. To do so, we use two different methods, often used together: <\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>The <code>read()<\/code> method<\/strong> take an optional argument that specifies the number of characters to read.<\/li>\n\n\n\n<li><strong>The <code>readline()<\/code> method<\/strong> is used to read a single line of a text file.<\/li>\n<\/ol>\n\n\n\n<p>Here is a practical example of how to read only the first 12 characters and the first line of a text file.<\/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 = open('example.txt', 'r')\nten_chars = file.read(12)\nprint(ten_chars)\n\nfirst_line = file.readline()\nprint(first_line)\nfile.close()\n<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-3-3-iterate-over-the-lines-of-a-text-file-in-python\"><span class=\"ez-toc-section\" id=\"33-iterate-over-the-lines-of-a-text-file-in-python\"><\/span>3.3 Iterate over the lines of a text file in Python<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>The <code>readline()<\/code> method we just saw above can of course be used in a loop to iterate over the lines of a text file. This is the more efficient way of reading a text file when compared to reading the entire file into memory.<\/p>\n\n\n\n<p>Below is another example of Python script, it iterates over all the lines of the text file called example.txt.<\/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 = open('example.txt', 'r')\nfor line in file:\n    print(line)\nfile.close()\n<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-3-4-read-a-file-line-by-line-and-store-it-in-a-list-with-python\"><span class=\"ez-toc-section\" id=\"34-read-a-file-line-by-line-and-store-it-in-a-list-with-python\"><\/span>3.4 Read a file line by line and store it in a list with Python<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>We can also read a text file line by line and store the data in a list or any other suitable <a href=\"https:\/\/expert-only.com\/en\/python\/python-data-types\/\">Python data structure<\/a>. The Python script below <strong>reads a text file line by line<\/strong> and store it in a list, called lines. Note that it is possible and recommended for long term storage, to use a SQL database.<\/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 = open('example.txt', 'r')\nlines = file.readlines()\nprint(lines)\nfile.close()\n<\/pre>\n\n\n\n<p>Please note that the <a href=\"https:\/\/expert-only.com\/en\/python\/introduction-to-python-programming\/\">Python programming language<\/a> provide an elegant way to handle file using the context manager. The context manager takes care of opening and closing the file automatically. I.e., In this example, you <strong>don&#8217;t have to explicitly close the 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=\"\">with open(\"example.txt\", \"r\") as file:\n    content = file.read()\n    print(content)\n<\/pre>\n\n\n\n<p>In the examples above, we&#8217;ve used the <code>.txt<\/code> file, but you can read any other file format as well, such as <code>.csv<\/code>, <code>.json<\/code>, etc.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-4-write-text-files-with-python-scripts\"><span class=\"ez-toc-section\" id=\"4-write-text-files-with-python-scripts\"><\/span>4. Write text files with Python scripts<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>In the following sections, we will cover more advanced operations such as writing to a text file and manipulating the contents of a text file.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-4-1-open-and-write-to-a-text-file-in-python\"><span class=\"ez-toc-section\" id=\"41-open-and-write-to-a-text-file-in-python\"><\/span>4.1 Open and write to a text file in Python<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>In Python, the <code>open()<\/code> function is used to open a file and the <code>write()<\/code> method is used to write to a file. The first argument of the <code>open()<\/code> function is the path to the file and the second argument is the mode in which the file should be opened. The mode <code>'w'<\/code> is used to open a file for writing, and truncates the file if it already exists. Here&#8217;s an example of how to open and write to a text file:<\/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('example.txt', 'w') as file:\n    file.write('Hello World')\n<\/pre>\n\n\n\n<p>In the script above, the file <code>example.txt<\/code> is opened in write mode and the string <code>'Hello World'<\/code> is written to the file. The <code>with open<\/code> statement is used to ensure that the file is properly closed after the operations inside the block are completed.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-4-2-write-to-a-specific-position-in-a-text-file\"><span class=\"ez-toc-section\" id=\"42-write-to-a-specific-position-in-a-text-file\"><\/span>4.2 Write to a specific position in a text file<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>The <code>seek()<\/code> method can be used to move the file pointer to a specific position in a file. The first argument of the <code>seek()<\/code> method is the position and the second argument is an optional value that defaults to <code>0<\/code>. Here&#8217;s an example of how to write to a specific position in a file, here it is the position 6, i.e., just after the word Hello and the space written just before.<\/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('example.txt', 'w') as file:\n    file.write('Hello ')\n    file.seek(6)\n    file.write('Universe')\n<\/pre>\n\n\n\n<p>In this example, the file <code>example.txt<\/code> is opened in write mode and the string <code>'Hello '<\/code> is written to the file. Then the file pointer is moved to position 6 using the <code>seek()<\/code> method and the string <code>'Universe'<\/code> is written to the file. This will change the text from &#8216;Hello &#8216; to &#8216;Hello Universe&#8217;<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-4-3-append-text-to-a-file-with-python\"><span class=\"ez-toc-section\" id=\"43-append-text-to-a-file-with-python\"><\/span>4.3 Append text to a file with Python<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>The mode <code>'a'<\/code> is used to open a file for appending. In this mode, any data written to the file is automatically appended to the end of the file. Here&#8217;s an example of how to append text to a file.<\/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('example.txt', 'a') as file:\n    file.write('Hello World')\n<\/pre>\n\n\n\n<p>In this example, the file <code>example.txt<\/code> is opened in append mode and the string <code>'Hello World'<\/code> is written to the file.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-4-4-write-to-a-file-line-by-line\"><span class=\"ez-toc-section\" id=\"44-write-to-a-file-line-by-line\"><\/span>4.4 Write to a file line by line<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>The <code>writelines()<\/code> method can be used to write a list of strings to a file, with each string as a separate line. Here&#8217;s an example of how to write to a file line by line:<\/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=\"\">lines = ['Hello', 'World']\nwith open('example.txt', 'w') as file:\n    file.writelines('\\n'.join(lines))\n<\/pre>\n\n\n\n<p>In this example, the list <code>lines<\/code> is created and contains two string elements <code>'Hello'<\/code> and <code>'World'<\/code>. Then the file <code>example.txt<\/code> is opened in write mode and the <code>writelines()<\/code> method is used to write the elements of the list to the file as separate lines.<\/p>\n\n\n\n<p>It is important to remember that when you are working with text files, it is recommended to always use the <code>with open<\/code> statement to ensure that the file is properly closed after the operations inside the block are completed.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"5-manipulate-data-in-text-files-using-python\"><\/span>5. Manipulate data in text files using Python<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>In this fourth section on <strong>how to manage files in Python<\/strong>, let&#8217;s see how to use Python scripts to manipulate text files. We will cover various operations such as searching for a specific string or pattern, replacing text, sorting lines, and extracting specific lines. Detailed explanations, methods and code examples will be provided for each use case to help you understand the process and apply it to your own projects.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"51-search-for-a-specific-string-using-the-find-method\"><\/span>5.1 Search for a specific string using the find method<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>Searching for a specific string in a text file can be done using the <code>str.find()<\/code> method or the <code>re<\/code> module for regular expressions. The <code>str.find()<\/code> method returns the index of the first occurrence of the specified string in the text file. If the specified string is not found, it returns -1. This script uses the <code>str.find()<\/code> Python method to search for a specific string in a text file.<\/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(\"example.txt\", \"r\") as file:\n    text = file.read()\n    index = text.find(\"example\")\n    if index != -1:\n        print(\"The string 'example' was found at index\", index)\n    else:\n        print(\"The string 'example' was not found in the text file.\")\n<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"52-search-specific-strings-using-search-method\"><\/span>5.2 Search specific strings using search method<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>The <code>re<\/code> module can also be used to search for a specific string by using the <code>search()<\/code> function. The <code>search()<\/code> function returns a match object if a match is found and <code>None<\/code> if no match is found. Here is an script to show how to use the <code>search()<\/code> function to search for a specific string in a txt file.<\/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=\"\">import re\n\nwith open(\"example.txt\", \"r\") as file:\n    text = file.read()\n    match = re.search(\"example\", text)\n    if match:\n        print(\"The string 'example' was found at index\", match.start())\n    else:\n        print(\"The string 'example' was not found in the text file.\")\n<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"53-search-for-a-specific-string-with-python\"><\/span>5.3 Search for a specific string with Python<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>Searching for a specific string in a text file can be done using the <code>str.find()<\/code> method or the <code>re<\/code> module for regular expressions. The <code>str.find()<\/code> method returns the index of the first occurrence of the specified string in the text file. If the specified string is not found, it returns -1. Find another way to search for a string inside a text file using, this time with the <code>str.find()<\/code> method.<\/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(\"example.txt\", \"r\") as file:\n    text = file.read()\n    index = text.find(\"example\")\n    if index != -1:\n        print(\"The string 'example' was found at index\", index)\n    else:\n        print(\"The string 'example' was not found in the text file.\")\n<\/pre>\n\n\n\n<p>The <code>re<\/code> module can also be used to search for a specific string by using the <code>search()<\/code> function. The <code>search()<\/code> function returns a match object if a match is found and <code>None<\/code> if no match is found. Use the <code>search()<\/code> function to search for a specific string in a txt file, as in the code below.<\/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=\"\">import re\n\nwith open(\"example.txt\", \"r\") as file:\n    text = file.read()\n    match = re.search(\"example\", text)\n    if match:\n        print(\"The string 'example' was found at index\", match.start())\n    else:\n        print(\"The string 'example' was not found in the text file.\")\n<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"54-search-patterns-with-findall-and-finditer\"><\/span>5.4 Search patterns with findall and finditer<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>Searching for a specific pattern in a text file can be done using the <code>re<\/code> module. The <code>findall()<\/code> function returns a list of all the matches in the text file. One more example of how to use the <code>findall()<\/code> function to search for a specific pattern in a text file.<\/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=\"\">import re\n\nwith open(\"example.txt\", \"r\") as file:\n    text = file.read()\n    matches = re.findall(\"[0-9]+\", text)\n    print(\"The following numbers were found in the text file:\", matches)\n<\/pre>\n\n\n\n<p>The <code>finditer()<\/code> function can also be used to search for a specific pattern in a text file. It returns an iterator yielding match objects.<\/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=\"\">import re\n\nwith open(\"example.txt\", \"r\") as file:\n    text = file.read()\n    for match in re.finditer(\"[A-Za-z]+\", text):\n        print(\"The word\", match.group(), \"was found at index\", match.start())\n<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"55-replace-a-text-in-a-file-in-python\"><\/span>5.5 Replace a text in a file in Python<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>To replace text in a file in Python, use the <code>replace()<\/code> method. This method replaces all occurrences of the specified string with another string. Here is another script to illustrate how to use the <code>replace()<\/code> method to replace text in a text file.<\/p>\n\n\n\n<p>It is important to note that when using the <code>replace()<\/code> method, <strong>the original file will be overwritten with the new text<\/strong>. Indeed, to keep the original file, create a backup copy or create new file and write the new text there.<\/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(\"example.txt\", \"w\") as file:\n    new_text = text.replace(\"old_text\", \"new_text\")\n    file.write(new_text)\nprint(\"Text replaced successfully.\")\n<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"56-python-script-to-sort-lines-of-a-file\"><\/span>5.6 Python script to sort lines of a file<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>When you manage files in Python programming project, and especially data, it is useful to sort the lines of a text file. It can be done by reading the file into a list, sorting the list, and then writing the list back to the file. It is important to note that this will sort the lines in alphabetical order by default. You can also use the <code>sorted()<\/code> function with a key function to sort the lines in a different order.<\/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(\"example.txt\", \"r\") as file:\n    lines = file.readlines()\nlines.sort()\nwith open(\"example.txt\", \"w\") as file:\n    file.writelines(lines)\nprint(\"Lines sorted successfully.\")\n<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"57-extract-specific-lines-from-a-txt-file\"><\/span>5.7 Extract specific lines from a txt file<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>Extracting specific lines from a text file can be done by reading the file into a list, and then using list slicing to extract the specific lines. As you can see, in this example, the <code>start<\/code> and <code>end<\/code> variables represent the starting and ending line numbers to extract from the text file. The extracted lines are then written to a new file called <em>new_file.txt<\/em>.<\/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(\"example.txt\", \"r\") as file:\n    lines = file.readlines()\nextracted_lines = lines[start:end]\nwith open(\"new_file.txt\", \"w\") as file:\n    file.writelines(extracted_lines)\nprint(\"Lines extracted successfully.\")\n<\/pre>\n\n\n\n<p>This tutorial on files is very useful on programming projects  using a large number of files, and it is using the <a href=\"https:\/\/expert-only.com\/en\/python\/python-strings\/\">Python strings<\/a> to handle the directories, the files and content.<\/p>\n\n\n\n<figure class=\"wp-block-embed is-type-wp-embed is-provider-sql-and-it-tutorials wp-block-embed-sql-and-it-tutorials\"><div class=\"wp-block-embed__wrapper\">\n<blockquote class=\"wp-embedded-content\" data-secret=\"wTnSV1Y8xD\"><a href=\"https:\/\/expert-only.com\/en\/python\/python-strings\/\">Python Strings<\/a><\/blockquote><iframe loading=\"lazy\" class=\"wp-embedded-content\" sandbox=\"allow-scripts\" security=\"restricted\" style=\"position: absolute; clip: rect(1px, 1px, 1px, 1px);\" title=\"&#8220;Python Strings&#8221; &#8212; SQL and IT Tutorials\" src=\"https:\/\/expert-only.com\/en\/python\/python-strings\/embed\/#?secret=8DFVia06KJ#?secret=wTnSV1Y8xD\" data-secret=\"wTnSV1Y8xD\" width=\"500\" height=\"282\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"no\"><\/iframe>\n<\/div><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-conclusion-on-managing-text-files-in-python\"><span class=\"ez-toc-section\" id=\"conclusion-on-managing-text-files-in-python\"><\/span>Conclusion on managing text files in Python<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>In conclusion, <strong>manage text files in Python<\/strong> is a simple and efficient process that can be done using the built-in functions and libraries such as <strong>open<\/strong>, <strong>read<\/strong>, <strong>write<\/strong>, and <strong>close<\/strong>. The use of the <a href=\"https:\/\/pandas.pydata.org\/pandas-docs\/stable\/getting_started\/install.html\" target=\"_blank\" rel=\"noreferrer noopener\">pandas<\/a> library can also be useful for handling larger and more complex files.<\/p>\n\n\n\n<p>By understanding the basic concepts and techniques for working with text files, you can easily develop your own programs and scripts to automate tasks and manipulate data. With this knowledge, you can now begin to explore the vast possibilities that text file management offers in the field of data science, machine learning, and data analysis.<\/p>\n","protected":false},"excerpt":{"rendered":"<div class=\"mh-excerpt\"><p>Python tutorial on how to manage text files using the open, read, readline, write, writelines, seek and close methods with scripts examples. This tutorial on how to manage text files in Python provide some information and code examples on <a class=\"mh-excerpt-more\" href=\"https:\/\/expert-only.com\/en\/python\/text-files-in-python\/\" title=\"Manage text files in Python using read and write methods\">&#8230;<\/a><\/p>\n<\/div>","protected":false},"author":1,"featured_media":6393,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[657],"tags":[],"class_list":{"0":"post-21494","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-python"},"yoast_head":"<!-- This site is optimized with the Yoast SEO Premium plugin v21.7 (Yoast SEO v26.2) - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>How to manage text files in Python ? Read and write - Python code<\/title>\n<meta name=\"description\" content=\"Tutorial to manage text files in Python using the read, write, iterate, search and sort methods with practical scripts 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:\/\/expert-only.com\/en\/python\/text-files-in-python\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Manage text files in Python using read and write methods\" \/>\n<meta property=\"og:description\" content=\"Tutorial to manage text files in Python using the read, write, iterate, search and sort methods with practical scripts examples.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/expert-only.com\/en\/python\/text-files-in-python\/\" \/>\n<meta property=\"og:site_name\" content=\"SQL and IT Tutorials\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/ExpertOnlyCom\/\" \/>\n<meta property=\"article:published_time\" content=\"2022-12-19T05:56:00+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-01-18T09:24:50+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/expert-only.com\/wp-content\/uploads\/2020\/07\/coffee-D35CDAFCD6A_1920x1080.jpeg\" \/>\n\t<meta property=\"og:image:width\" content=\"1920\" \/>\n\t<meta property=\"og:image:height\" content=\"1080\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"Expert-Only\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@expert_only\" \/>\n<meta name=\"twitter:site\" content=\"@expert_only\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Expert-Only\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"19 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/expert-only.com\/en\/python\/text-files-in-python\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/expert-only.com\/en\/python\/text-files-in-python\/\"},\"author\":{\"name\":\"Expert-Only\",\"@id\":\"https:\/\/expert-only.com\/en\/#\/schema\/person\/406a9576b52944f018739a42046873ef\"},\"headline\":\"Manage text files in Python using read and write methods\",\"datePublished\":\"2022-12-19T05:56:00+00:00\",\"dateModified\":\"2023-01-18T09:24:50+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/expert-only.com\/en\/python\/text-files-in-python\/\"},\"wordCount\":3171,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/expert-only.com\/en\/#organization\"},\"image\":{\"@id\":\"https:\/\/expert-only.com\/en\/python\/text-files-in-python\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/expert-only.com\/wp-content\/uploads\/2020\/07\/coffee-D35CDAFCD6A_1920x1080.jpeg\",\"articleSection\":[\"Python tutorials\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/expert-only.com\/en\/python\/text-files-in-python\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/expert-only.com\/en\/python\/text-files-in-python\/\",\"url\":\"https:\/\/expert-only.com\/en\/python\/text-files-in-python\/\",\"name\":\"How to manage text files in Python ? Read and write - Python code\",\"isPartOf\":{\"@id\":\"https:\/\/expert-only.com\/en\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/expert-only.com\/en\/python\/text-files-in-python\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/expert-only.com\/en\/python\/text-files-in-python\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/expert-only.com\/wp-content\/uploads\/2020\/07\/coffee-D35CDAFCD6A_1920x1080.jpeg\",\"datePublished\":\"2022-12-19T05:56:00+00:00\",\"dateModified\":\"2023-01-18T09:24:50+00:00\",\"description\":\"Tutorial to manage text files in Python using the read, write, iterate, search and sort methods with practical scripts examples.\",\"breadcrumb\":{\"@id\":\"https:\/\/expert-only.com\/en\/python\/text-files-in-python\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/expert-only.com\/en\/python\/text-files-in-python\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/expert-only.com\/en\/python\/text-files-in-python\/#primaryimage\",\"url\":\"https:\/\/expert-only.com\/wp-content\/uploads\/2020\/07\/coffee-D35CDAFCD6A_1920x1080.jpeg\",\"contentUrl\":\"https:\/\/expert-only.com\/wp-content\/uploads\/2020\/07\/coffee-D35CDAFCD6A_1920x1080.jpeg\",\"width\":1920,\"height\":1080},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/expert-only.com\/en\/python\/text-files-in-python\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"en\",\"item\":\"https:\/\/expert-only.com\/en\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Manage text files in Python using read and write methods\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/expert-only.com\/en\/#website\",\"url\":\"https:\/\/expert-only.com\/en\/\",\"name\":\"SQL and IT Tutorials\",\"description\":\"\",\"publisher\":{\"@id\":\"https:\/\/expert-only.com\/en\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/expert-only.com\/en\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/expert-only.com\/en\/#organization\",\"name\":\"Expert-Only\",\"url\":\"https:\/\/expert-only.com\/en\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/expert-only.com\/en\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/expert-only.com\/wp-content\/uploads\/2017\/09\/cropped-logo_Expert-Only.jpg\",\"contentUrl\":\"https:\/\/expert-only.com\/wp-content\/uploads\/2017\/09\/cropped-logo_Expert-Only.jpg\",\"width\":381,\"height\":174,\"caption\":\"Expert-Only\"},\"image\":{\"@id\":\"https:\/\/expert-only.com\/en\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/ExpertOnlyCom\/\",\"https:\/\/x.com\/expert_only\",\"https:\/\/www.youtube.com\/channel\/UCMS5sR_FwAetB0FmciNvUaA\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/expert-only.com\/en\/#\/schema\/person\/406a9576b52944f018739a42046873ef\",\"name\":\"Expert-Only\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/expert-only.com\/en\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/084b15660763ff5b13bb60b2f52f97bb?s=96&d=identicon&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/084b15660763ff5b13bb60b2f52f97bb?s=96&d=identicon&r=g\",\"caption\":\"Expert-Only\"}}]}<\/script>\n<!-- \/ Yoast SEO Premium plugin. -->","yoast_head_json":{"title":"How to manage text files in Python ? Read and write - Python code","description":"Tutorial to manage text files in Python using the read, write, iterate, search and sort methods with practical scripts 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:\/\/expert-only.com\/en\/python\/text-files-in-python\/","og_locale":"en_US","og_type":"article","og_title":"Manage text files in Python using read and write methods","og_description":"Tutorial to manage text files in Python using the read, write, iterate, search and sort methods with practical scripts examples.","og_url":"https:\/\/expert-only.com\/en\/python\/text-files-in-python\/","og_site_name":"SQL and IT Tutorials","article_publisher":"https:\/\/www.facebook.com\/ExpertOnlyCom\/","article_published_time":"2022-12-19T05:56:00+00:00","article_modified_time":"2023-01-18T09:24:50+00:00","og_image":[{"width":1920,"height":1080,"url":"https:\/\/expert-only.com\/wp-content\/uploads\/2020\/07\/coffee-D35CDAFCD6A_1920x1080.jpeg","type":"image\/jpeg"}],"author":"Expert-Only","twitter_card":"summary_large_image","twitter_creator":"@expert_only","twitter_site":"@expert_only","twitter_misc":{"Written by":"Expert-Only","Est. reading time":"19 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/expert-only.com\/en\/python\/text-files-in-python\/#article","isPartOf":{"@id":"https:\/\/expert-only.com\/en\/python\/text-files-in-python\/"},"author":{"name":"Expert-Only","@id":"https:\/\/expert-only.com\/en\/#\/schema\/person\/406a9576b52944f018739a42046873ef"},"headline":"Manage text files in Python using read and write methods","datePublished":"2022-12-19T05:56:00+00:00","dateModified":"2023-01-18T09:24:50+00:00","mainEntityOfPage":{"@id":"https:\/\/expert-only.com\/en\/python\/text-files-in-python\/"},"wordCount":3171,"commentCount":0,"publisher":{"@id":"https:\/\/expert-only.com\/en\/#organization"},"image":{"@id":"https:\/\/expert-only.com\/en\/python\/text-files-in-python\/#primaryimage"},"thumbnailUrl":"https:\/\/expert-only.com\/wp-content\/uploads\/2020\/07\/coffee-D35CDAFCD6A_1920x1080.jpeg","articleSection":["Python tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/expert-only.com\/en\/python\/text-files-in-python\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/expert-only.com\/en\/python\/text-files-in-python\/","url":"https:\/\/expert-only.com\/en\/python\/text-files-in-python\/","name":"How to manage text files in Python ? Read and write - Python code","isPartOf":{"@id":"https:\/\/expert-only.com\/en\/#website"},"primaryImageOfPage":{"@id":"https:\/\/expert-only.com\/en\/python\/text-files-in-python\/#primaryimage"},"image":{"@id":"https:\/\/expert-only.com\/en\/python\/text-files-in-python\/#primaryimage"},"thumbnailUrl":"https:\/\/expert-only.com\/wp-content\/uploads\/2020\/07\/coffee-D35CDAFCD6A_1920x1080.jpeg","datePublished":"2022-12-19T05:56:00+00:00","dateModified":"2023-01-18T09:24:50+00:00","description":"Tutorial to manage text files in Python using the read, write, iterate, search and sort methods with practical scripts examples.","breadcrumb":{"@id":"https:\/\/expert-only.com\/en\/python\/text-files-in-python\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/expert-only.com\/en\/python\/text-files-in-python\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/expert-only.com\/en\/python\/text-files-in-python\/#primaryimage","url":"https:\/\/expert-only.com\/wp-content\/uploads\/2020\/07\/coffee-D35CDAFCD6A_1920x1080.jpeg","contentUrl":"https:\/\/expert-only.com\/wp-content\/uploads\/2020\/07\/coffee-D35CDAFCD6A_1920x1080.jpeg","width":1920,"height":1080},{"@type":"BreadcrumbList","@id":"https:\/\/expert-only.com\/en\/python\/text-files-in-python\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"en","item":"https:\/\/expert-only.com\/en\/"},{"@type":"ListItem","position":2,"name":"Manage text files in Python using read and write methods"}]},{"@type":"WebSite","@id":"https:\/\/expert-only.com\/en\/#website","url":"https:\/\/expert-only.com\/en\/","name":"SQL and IT Tutorials","description":"","publisher":{"@id":"https:\/\/expert-only.com\/en\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/expert-only.com\/en\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/expert-only.com\/en\/#organization","name":"Expert-Only","url":"https:\/\/expert-only.com\/en\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/expert-only.com\/en\/#\/schema\/logo\/image\/","url":"https:\/\/expert-only.com\/wp-content\/uploads\/2017\/09\/cropped-logo_Expert-Only.jpg","contentUrl":"https:\/\/expert-only.com\/wp-content\/uploads\/2017\/09\/cropped-logo_Expert-Only.jpg","width":381,"height":174,"caption":"Expert-Only"},"image":{"@id":"https:\/\/expert-only.com\/en\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/ExpertOnlyCom\/","https:\/\/x.com\/expert_only","https:\/\/www.youtube.com\/channel\/UCMS5sR_FwAetB0FmciNvUaA"]},{"@type":"Person","@id":"https:\/\/expert-only.com\/en\/#\/schema\/person\/406a9576b52944f018739a42046873ef","name":"Expert-Only","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/expert-only.com\/en\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/084b15660763ff5b13bb60b2f52f97bb?s=96&d=identicon&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/084b15660763ff5b13bb60b2f52f97bb?s=96&d=identicon&r=g","caption":"Expert-Only"}}]}},"_links":{"self":[{"href":"https:\/\/expert-only.com\/en\/wp-json\/wp\/v2\/posts\/21494","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/expert-only.com\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/expert-only.com\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/expert-only.com\/en\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/expert-only.com\/en\/wp-json\/wp\/v2\/comments?post=21494"}],"version-history":[{"count":0,"href":"https:\/\/expert-only.com\/en\/wp-json\/wp\/v2\/posts\/21494\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/expert-only.com\/en\/wp-json\/wp\/v2\/media\/6393"}],"wp:attachment":[{"href":"https:\/\/expert-only.com\/en\/wp-json\/wp\/v2\/media?parent=21494"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/expert-only.com\/en\/wp-json\/wp\/v2\/categories?post=21494"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/expert-only.com\/en\/wp-json\/wp\/v2\/tags?post=21494"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}