How to Read Text File in Python

Posted on

Introduction

A little bit more of a detail explanation from the previous article. That previous article is ‘How to Input File in Python’ in this link. Basically, that article is just showing or discussing information about how to retrieve file as an input. In that article, there is an example for opening a file. Specifically, it is a text file where the ‘open()’ method does not have any additional parameter. When the execution of ‘open()’ method is just using one single parameter for specifying the file name, it will be by default implement ‘read’ mode for opening that file. The following is the default syntax for opening the file as a reminder :

text_file = open('text_file_name.txt')

How to Read Text File in Python

So, using the above information in the previous part, the following is an actual process for reading text file in Python programming language. But the first execution will be just trying to print out the type of the variable which is actually  a text file as follows :

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.
>>> text_content = open('text_file.txt');
>>> print(text_content);
<_io.TextIOWrapper name='text_file.txt' mode='r' encoding='cp1252'>
>>> quit()
C:\python>

But the main purpose for reading the text file in Python programming language is not printing the data type of the variable. Instead, the main purpose is just to be able to print the content inside of it. Before going on further, the following is the actual content of a text with the name ‘text_file.txt’ as an example :

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

So, below is the actual command execution directly in the Python command console and also directly executing a Python programming language’s source code to be able to print the content :

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.
>>> text_content = open('text_file.txt','r');
>>> print(text_content);
<_io.TextIOWrapper name='text_file.txt' mode='r' encoding='cp1252'>
>>> text_content = text_content.read();
>>> print(text_content);
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