read and readline
- Python course
- Intermediate
- Lesson 65/116
- 4 min
Learn reading with read and readline.
read returns all content
The file object's read() method returns the whole file content as a single string. If you pass a number like read(10), it reads only the first 10 characters. For large files, loading everything into memory at once can be a problem; reading in chunks is then preferred.
readline() returns one line per call. It includes the trailing \n; the last line may not have it. When it returns an empty string, you've reached the end of the file.
readlines for a list of lines
The readlines() method returns all lines as a list. Each item is one line, with its \n at the end. You can get the line count with len(lines).
This method is handy for small and medium files. On very large files it can fill memory; the loop for line in f: walks one line at a time and is gentler on memory.
Practice Write two lines, read with readlines
Open a file for writing: f = open("two.txt", "w", encoding="utf-8"). Write f.write("First line\nSecond line") and close it. Reopen it in read mode and get the lines with lines = f.readlines(). Print the count with print(len(lines)) and close it.
Starter code
# Write two lines to the file and close
# Reopen, get lines with readlines, print the countSample solution
# Write two lines to the file and close
f = open("two.txt", "w", encoding="utf-8")
f.write("First line\nSecond line")
f.close()
# Reopen, get lines with readlines, print the count
f = open("two.txt", "r", encoding="utf-8")
lines = f.readlines()
print(len(lines))
f.close()Expected output
2
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Call the read method
f = open("notes.txt", encoding="utf-8")
content = f.____()
print(content)
f = open("notes.txt", encoding="utf-8")
content = f.read()
print(content)
Explanation: read() returns all content as a single string.
2 What does readline() return at end of file?
- Repeats the last line
- Raises an error
- Returns an empty string Correct answer
- Returns None
Explanation: At end of file, readline() returns an empty string ("").
3 Match the reading methods
| Term | Meaning |
|---|---|
read |
Returns all content |
readline |
Returns one line |
readlines |
Returns a list of lines |
close |
Closes the file |