How to Read a Text File in Python

To read a text file in Python:

  1. Open the file.
  2. Read the lines from the file.
  3. Close the file.

For example, let’s read a text file called example.txt from the same folder of the code file:

with open('example.txt') as file:
    lines = file.readlines()

Now the lines variable stores all the lines from example.txt as a list of strings.

This is the quick answer.

To learn more details about reading files in Python, please read along.

In this guide, you learn how to securely read a file in Python. In addition, you are going to see a bunch of useful file-reading methods, including:

  • open()
  • read()
  • readline()
  • readlines()

What Is a File in a Computer’s Perspective?

Before reading a file, you need to take a deeper dive into the world of files.

This is because you want to know what a computer program sees when dealing with files.

This makes understanding and building file-reading logic easier for you.

Essentially, a file is a collection of bytes used to store data. This byte data is organized in a special format that builds up a file. A file can be something simple like a text file or something more complex like an executable program file.

No matter what type of file you have, in the end, it is converted to 0s and 1s for a computer to understand.

A file is composed of three main parts:

  1. Header. The header consists of the metadata about the file, such as name, size, type, and so on.
  2. Data. The contents of the file.
  3. End of File (EOF). A special hidden character that highlights the end of the file.

In this guide, we are only going to work with .txt files. However, keep in mind that there are thousands of different file extensions.

File Paths

Whenever you try to access a file on your system, you need to specify the path to the file.

Thus, it is not enough to just call the file by its name.

A file path is nothing but a string that points to the location of the file.

The file path can be split into three parts:

  1. Folder path. The folder’s location in the file system. Subsequent folders are separated by backslashes (/) or forward slashes (\) depending on your system.
  2. Filename. The name of the file.
  3. Extension. The end of the file with the “.”, such as .txt or .jpeg. This defines the type of file in question.

An example of a file path could be something like this:

Desktop/Projects/FileReader/example.py

When you write a Python program to read a file, you need to know the path of the file. Then you need to make the program read the contents of the file until the EOF character is reached.

This might sound more complex than it actually is.

Python does a lot of automation behind the scenes for you. This makes it possible for you to read an entire file with 2 lines of code, as you shall see.

Let’s jump into reading Python files.

Reading Text Files in Python

One of the most common tasks in Python is to read/write to an external file.

This can be something simple, such as a text file. But a file could be something more complex, such as a server log or byte file.

To deal with any of these files, you need to understand how to read and write a file in Python.

In this guide, we are going to focus on reading files.

Reading a text file into your Python program follows this procedure:

  1. Open the file with the built-in open() function by specifying the path of the file into the call.
  2. Read the text from the file using one of these methods: read(), readline(), readlines().
  3. Close the file using the close() method. You can let Python handle closing the file automatically by opening the file using the with statement.

1. How to Use the open() Function in Python

The basic syntax for calling the open() function is:

open(path_to_a_file, mode)

Where:

  • path_to_a_file is the path to the file you want to open. For example Desktop/Python/example.txt. If your python program file is in the same folder as the text file, the path is just the name of the file.
  • mode specifies in which state you want to open the file. There are multiple options. But as you’re interested in reading a file, you only need the mode ‘r’.

The open() function returns an iterable file object with which you can easily read the contents of the file.

For instance, if you have a file called example.txt in the same folder as your code file, you can open it by:

file = open("example.txt", "r")

Now the file is opened, but not been used in any useful way yet.

Next, let’s take a look at how to actually read the opened file in Python.

2. File Reading Methods in Python

To read an opened file, let’s focus on the three different text reading methods: read(), readline(), and readlines():

  • read() reads all the text from a file into a single string and returns the string.
  • readline() reads the file line by line and returns each line as a separate string.
  • readlines() reads the file line by line and returns the whole file as a list of strings, where each string is a line from the file.

Later you are going to see examples of each of these methods.

For instance, let’s read the contents of a file called “example.txt” to a variable as a string:

file = open("example.txt")
contents = file.read()

Now the contents variable has whatever is inside the file as a single long string.

3. Always Close the File in Python

In Python, an opened file remains open as long as you don’t close it. So make sure to close the file after using it. This can be done with the close() method. This is important because the program can crash or the file can corrupt if left hanging open.

file.close()

You can also let Python take care of closing the file by using the with statement when dealing with files. In this case, you don’t need the close() method at all.

The with statement structure looks like this:

with open(path_to_file) as file:
    #read the file here

Using the with statement is so convenient and conventional, that we are going to stick with it for the rest of the guide.

Now you understand the basics of reading files in Python. Next, let’s have a look at reading files in action using the different reading functions.

Using the File Reading Methods in Python

To repeat the following examples, create a folder that has the following two files:

  • A reader.py file for reading text files.
  • An example.txt file from where your program reads the text.

Also, write some text on multiple lines into the example.txt file.

The read() method in Python

To read a file to a single string, use the read() method. As discussed above, this reads whatever is in the file as a single long string into your program.

For example, let’s read and print out the contents of the example.txt file:

with open("example.txt") as file:
    contents = file.read()
    print(contents)

Running this piece of code displays the contents of example.txt in the console:

Hi
This is just an example
I demonstrate reading lines

The readline() Method in Python

To read a file one line at a time, use the readline() method. This reads the current line in the opened file and moves the line pointer to the next line. To read the whole file, use a while loop to read each line and move the file pointer until the end of the file is reached.

For example:

with open('example.txt') as file:
     next_line = file.readline()
     while next_line:
         print(next_line)
         next_line = file.readline()

As a result, this program prints out the lines one by one as the while loop proceeds:

Hi

This is just an example

I'm demonstrate reading lines

The readlines() Method in Python

To read all the lines of a file into a list of strings, use the readlines() method.

When you have read the lines, you can loop through the list of lines and print them out for example:

with open('example.txt') as file:
    lines = file.readlines()
    line_num = 0
    for line in lines:
        line_num += 1
        print(f"line {line_num}: {line}")  

This displays each line in the console:

line 1: Hi

line 2: This is just an example

line 3: I'm demonstrate reading lines

Use a For Loop to Read an Opened File

You just learned about three different methods you can use to read a file into your Python program.

It is good to realize that the open() function returns an iterable object. This means that you can loop through an opened file just like you would loop through a list in Python.

For example:

with open('example.txt') as file:
     for line in file:
         print(line)

Output:

Hi

This is just an example

I'm demonstrate reading lines

As you can see, you did not need to use any of the built-in file reading methods. Instead, you used a for loop to run through the file line by line.

Conclusion

Today you learned how to read a text file into your Python program.

To recap, reading files follows these three steps:

  1. Use the open() function with the ‘r’ mode to open a text file.
  2. Use one of these three methods: read()readline(), or readlines() to read the file.
  3. Close the file after reading it using the close() method or let Python do it automatically by using the with statement.

Conventionally, you can also use the with statement to reading a file. This automatically closes the file for you so you do not need to worry about the 3rd step.

Thanks for reading. Happy coding!

Further Reading