Python with
On the last page you wrote close yourself. A stop before that line could leave the file open. with closes the file when the indented lines are finished. It still closes the file if one of those lines stops.
with open("plate.txt", "w", encoding="utf-8") as plate:
plate.write("bread\n")
print("saved")
The screen shows saved. bread is in plate.txt, not on the screen. write ran while the file was open. The indent ended, the file closed, and only then did print run. This program does not contain close(). Do not add one after print, and do not put one inside the indent either. The name plate means the open file, and only until the indent ends. encoding="utf-8" keeps the letters as text. w still clears whatever older words were in the file.
The write line is indented under with. That indent is what puts the line inside. print("saved") is not indented, so it sits outside. It runs only when the inside has finished.
Write 1 / 0 under that same indent and the program stops. saved is not written. The file still closes, because leaving the indent closes it before the program ends on that stop. That line is not in the program on this page.
The next page is the path of the file. This page only closes the file.
The file closes when the indent ends
The screen shows saved. plate.txt holds bread. close() is not in this program. If a line inside the indent stops, the file still closes and saved is not written. The next page is the path of the file.
🧠 Test Your Knowledge
Test Your Knowledge
Challenge yourself with this interactive quiz and see how well you understand the topic
📝 Instructions
- Read each question carefully
- Select the best answer for each question
- You can retake the quiz as many times as you want
- Your progress will be shown at the top