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 Programming Course & Exercises

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

Examples

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 file.py and run it.

1
2
3
4
5
6
7
8
#!/usr/bin/env python

filename = "file.py"

with open(filename) as f:
content = f.readlines()

print(content)

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
2
3
4
5
6
7
8
9
#!/usr/bin/env python

filename = "file.py"

infile = open(filename, 'r')
data = infile.read()
infile.close()

print(data)

If you are a beginner, then I highly recommend this YouTube Python Playlist.

Exercise

  1. Read a file and number every line
  2. Find out what the program does if the file doesnג€™t exist.
  3. What happens if you create a file with another user and try to open it?