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.
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.
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:
- Read a file and number every line