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.
Practice now: Test your Python skills with interactive challenges
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.
#!/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:
#!/usr/bin/env python
filename = "file.py"
infile = open(filename, 'r')
data = infile.read()
infile.close()
print(data)
Practice now: Test your Python skills with interactive challenges
Practice Exercises
- Read a file and number every line
- Find out what the program does if the file doesn't exist.
- What happens if you create a file with another user and try to open it?