Lesson 05
Reading Files — read() and readlines()
Read a Python text file with read() into one string, or with readlines() into a list of lines, and handle a missing file.
Reading transfers a record from the file back into an object in memory. read() builds one string. readlines() builds a list of lines.
Use the playground at the bottom of this page, then take the quiz.
What you will learn
- The three steps of a read operation
read()and the string it returnsreadlines()and the list it returns- What a missing file raises
- What
read()does at the end of the file
The idea
The steps are:
- Choose a file name that already exists.
- Open it in a read mode.
"r"is the usual choice. - Call
read()orreadlines().
text = handle.read() pulls the entire file into one string.
lines = handle.readlines() pulls the entire file into a list. Each item is one line, and the newline characters stay on those items.
Both methods move through the file from the current pointer. A second read() on the same open pointer returns "" because the pointer is already at the end. That empty string is not EOFError. EOFError shows up in other tools, such as an empty pickle load, not as the normal result of read().
If the name does not exist, opening in "r" raises FileNotFoundError. Catch it when the file is optional. Link this to try and except.
read() and readlines() still return the record piece by piece in the sense that you asked for the whole text as characters or lines. When you need the original Python object back in one read, use unpickling.
Example
try:
with open("notebook.txt", "r", encoding="utf-8") as handle:
whole = handle.read()
print(whole)
with open("notebook.txt", "r", encoding="utf-8") as handle:
lines = handle.readlines()
print(lines)
except FileNotFoundError:
print("That file does not exist")The playground writes three lines first so the read has something to find. lines includes the newline on each item. A missing name takes the except branch.
Key takeaways
-
Open an existing name in read mode, then read
-
read()returns one string -
readlines()returns a list of line strings -
A missing file raises
FileNotFoundError -
A further
read()at the end returns an empty string -
Previous: write() and writelines()
-
Next: tell() and seek()
Loading playground…
Check your understanding
Reading files quiz
read() returns:
1 / 10