How to Read Text File per Line in Python

Posted on

Introduction

It is a continuation from the previous article. Actually, the previous article is actually discussing the same subject. That article with the title of ‘How to Read Text File in Python’ in this link is focusing the content for showing how to read text file in Python programming language. In the previous article, it is reading the text file using the ‘read()’ method. Basically, it is reading the file as is. But there is another method exist for reading in a certain manner. In that term, the file reading is in the manner or in the way that it will be read line per line one by one.

How to Read Text File per Line in Python

So, the main purpose in this article is actually has a similar one from the previous one which is reading the content of the text file. But the main difference is on how to read the content. In the previous article, it just read the content as is without any specific treatment in it. But in this context, it is reading the text file per line one by one. The result is a list collection data type variable where each data represent each line. Furthermore, the reading process line by line is using a different function or method. Actually, the normal reading process is using ‘read()’ method. On the other hand, the reading process line by line is using ‘readlines()’ method. Below is the steps to be able to do that :

  1. As always, the first step is just accessing Python command console since the process can just use it directly without having to create a Python source code file for demonstration.

    C:\python>python
    Python 3.10.5 (tags/v3.10.5:f377153, Jun  6 2022, 16:14:13) [MSC v.1929 64 bit (AMD64)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    
  2. Next, just execute the command for opening the file as an input as in the following source code below :

    >>> file_content = open('text_file.txt');
  3. After that, just perform the command for reading file per line as in the execution of the source code below :

    >>> text_content = file_content.readlines();
  4. Finally, below is the script of the source code for execution to display the content of the text file :

    >>> print(text_content);
    ['This is a text file sample\n', 'This is the second line of the text file sample\n', 'This is the third line from the text file sample']
    

    As in the above output source code execution, the print result is in a list collection data type.

  5. Another different version for printing the content of the text file using ‘for’ loop exist below :

    >>> for i in range(len(text_content)):
    ... print(text_content[i]);
    ...
    This is a text file sample
    This is the second line of the text file sample
    This is the third line from the text file sample
    >>>
    

Leave a Reply