Would you like to learn how to read a text file using Python? In this tutorial, we are going to show you how to use Python to read a line from a text file on a computer running Windows.

• Ubuntu 20
• Ubuntu 19
• Ubuntu 18
• Python 3

Equipment list

The following section presents the list of equipment used to create this tutorial.

As an Amazon Associate, I earn from qualifying purchases.

Tutorial Python - Read a text file

Install Python 3.

Copy to Clipboard

Create a text file.

Copy to Clipboard

Here is the file content.

Copy to Clipboard

In our example, we create a text file named NAMES in the TMP directory.

Read from a text file using Python.

Copy to Clipboard

Create a Python script to read a text file and print it on the screen.

Copy to Clipboard

Here is the file content.

Copy to Clipboard

Run the Python script.

Copy to Clipboard

Here is the command output.

Copy to Clipboard

Read the entire file using Python and the WITH statement.

Copy to Clipboard

Here is the command output.

Copy to Clipboard

Congratulations! You are able to read a text file using Python.

Tutorial Python - Read lines from a text file

Create a Python script to read lines from a text file and print it on the screen.

Copy to Clipboard

Here is the file content.

Copy to Clipboard

Run the Python script.

Copy to Clipboard

Here is the command output.

Copy to Clipboard

Optionally, print the read line without empty lines.

Copy to Clipboard

Here is the command output.

Copy to Clipboard

Optionally, use the WITH statement to open and close the file.

Copy to Clipboard

Here is the command output.

Copy to Clipboard

Optionally, use a Python lib to print the read text line without empty lines.

Copy to Clipboard

Here is the command output.

Copy to Clipboard

Read each line individually using Python.

Copy to Clipboard

Here is the command output.

Copy to Clipboard

Congratulations! You are able to read lines from a text file using Python.