open() hands you a handle to a file on disk; write and read move text through it, and with makes sure it is always closed.
1 Handles, Not Files
open() gives you a handle — a remote control aimed at a file on disk.
2 Modes Matter
"w" wipes, "a" appends, "r" reads — the mode letter decides the superpowers.
3 with = No Leaks
The with statement closes the file the instant its block ends — even on errors.
4 Text In, Text Out
write() sends strings; read() returns one big string with \n markers inside.
Files: data that outlives the program
Handles, Not Files1open() gives you a handle — a remote control aimed at a file on disk. Modes Matter2"w" wipes, "a" appends, "r" reads — the mode letter decides the superpowers. with = No Leaks3The with statement closes the file the instant its block ends — even on errors. Text In, Text Out4write() sends strings; read() returns one big string with \n markers inside. 4 building blocks make up Files: data that outlives the program
Press Run to follow diary.txt from creation to its first full read.
Tab one writes and appends by hand; tab two reads the same file with the with statement.
mainMode "w" CREATES the file (or wipes it) and hands back a handle for writing.
Console
output appears as the program runs…
f.read() starts at the top, and the cursor moves forward as text is consumed.
Drag to orbit the scene. Press Play to watch memory in action.
Click a term, then click its description to lock the pair.
6 conceptsTap a card to expand ?open("f.txt", "w")drops into place
?open("f.txt", "a")drops into place
?open("f.txt", "r")drops into place
?f.read()drops into place
?with open(...) as f:drops into place
?f.close()drops into place
Three writes, one read — what lands in the file?
Your predicted output — one line per console line
Hint: Each write continues where the last stopped — three digits make "123". read() returns them as one string, so len is 3.
01open("f.txt", "w") creates or wipes; "a" appends; "r" reads an existing file.
02Writes continue exactly where the previous one stopped.
03f.close() flushes and releases — always pair every open with a close.
04with open(...) as f: closes automatically when the block ends.
05read() returns the entire content as one string; len counts the invisible \n marks too.