๐
STUDENT NOTES ยท DAY 13 OF 24
The Memory Chest ๐
Close your program and every variable vanishes. Files are the treasure chest where data survives.
1Writing your first file
๐ค
Bittu: Variables live in my short-term memory โ poof at shutdown. Files go on the DISK. They survive restarts, power cuts, everything.
๐ฆ
Professor Hoot: The with block closes the file automatically when done. Always use it โ no forgotten open files.
2Reading it back
3The three modes
๐ "w" write โ wipes the file and starts fresh! โ "a" append โ adds at the end ๐ "r" read โ just looks
๐
Bugly: Heheheโฆ open an important file with "w" by mistake and everything inside is GONE. My masterpiece.
4Reading a file that isn't there
๐
Py: FileNotFoundError โ read mode needs the file to exist. Tomorrow we learn to catch errors like this gracefully!
5Quick quiz! ๐ง
You open an existing diary with open("diary.txt", "w"). What happens to the old entries?
๐ก "w" erases and starts over. To add to the end, use "a" for append.
Why use with open(...) as f:?
๐ก The with-block guarantees cleanup โ the file closes even if something goes wrong inside.
6Your mission ๐
Mission 1: Write your 3 favourite movies to movies.txt, one per line.
Mission 2: Read the file back and print each line with a loop.
Mission 3: Append a 4th movie with "a" mode, re-read, and confirm all 4 are there.
Day 13 done โ your programs have memory now! ๐พ
Next: exception handling โ programs that survive mistakes instead of crashing.
Go to Day 14: Error Shields โ