Reading a file
Python · Unit 17: Files
- Full plan
- Python
- 10 exercises
open(name) with no mode opens the file for reading, and read() returns the whole file as a single text.
with is the right habit for reading too. The line print(open(...).read()) is just the shortcut for a quick peek.
with open("today.txt", "w") as f:
f.write("bread\nmilk\n")
with open("today.txt") as f:
text = f.read()
print(text)
print(len(text))Prints
bread milk 11
The rest of the explanation is in the lesson, which is part of the full plan.
Exercises in this lesson
You do them in the app, which checks them on the spot and explains why.
1. Predict the output
What does this code print?
2. Complete the code
Complete it to show the whole file as a single text.
3. Predict the output
What does this code print?
4. Complete the code
Complete it to show each name without the line break.
5. Put the lines in order
Put the lines in order to save two colors and show the list of lines.
6. Predict the output
What does this code print?
7. Find the case that fails
first(text)savestextin a file and should return its first line, or""if the file ended up empty. Which call breaks it?8. Find the bug
This program should show what was saved. Which line has the bug?
9. Predict the output
What does this code print?
10. Predict the output
What does this code print?
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.