< previous | Table of Contents | next > |
7.4 READING FROM FILES
Reading from files allows us to access the contents of the file.
READING THE ENTIRE FILE AT ONCE
We can use the .read()
method to read the entire file. It loads the entire content of the file into a single string.
Here's an example in Thonny of how we can use this method.
READING FROM THE FILE LINE BY LINE
The .readline()
method reads and returns one line from the file, including the newline character at the end of the line. This enables us to process the file one line at a time without loading the entire file into memory.
Here, we create a while
loop to iterate over all the text file lines. We break out of the loop once we've hit the end of the file.
.readlines()
method reads all lines in a file and returns them as a list of strings. Each string in the list represents one line from the file. Hence, we’re able to iterate over them with a for
loop.
In the context of this course, it’s rather a matter of preference of which method you'd like to use.
KEY THINGS TO REMEMBER
- In case there is more than one line in the file, we should use a
for
loop to iterate over all the lines in the file. read()
reads the entire content of a file into a single string.readline()
reads and returns one line from the file at a time, including the newline character/n
at the end of the string.readlines()
reads all lines from a file and returns them as a list of strings.
SELF-CONTROL EXERCISES
< previous | Table of Contents | next > |