This post will discuss how to read a text file in Python.

1. Using open() function

A simple solution is to open the file in reading mode 'r' using the built-in open() function. Since the mode in which the file is opened defaults to 'r', you can skip it.

Download Code

 
The above syntax requires you to explicitly close the file using the close() function. This is not considered Pythonic, and you should use the with keyword, which automatically closes the file once it is done with, even when an exception is raised. Here’s an equivalent code using the with statement:

Download Code

2. Using pathlib module

You can also use the pathlib module with Python 3.4. The Path.read_text() function opens the file in text mode, reads it, and close the file.

Download Code

3. Using io module

Finally, you can call the io.open() function, which is an alias for the built-in open() function.

Download Code

That’s all about reading a file in Python.