Read file

Reading files is part of the Python standard library.  This means you do not have to include any module.

There are two ways to read files:

  • line by line
  • read block

In this article we will show you both methods.

Related course:
Complete Python Bootcamp: Go from zero to hero in Python

The solution you use depends on the problem you are trying to solve.


Line by line
To read files, you can use the readlines() function. This will read a file line by line and store it into a list:

Type the code below, save it as and run it.

Read block
You may not always want to read a file line by line. Take for example, if your file does not have newlines or is a binary file. To read a file and store into a string, use the read() function instead:


1. Read a file and number every line