File Handling
Programs can read and write files.
A file is like a notebook on disk.
You open it, do work, then close it.
Python makes this pretty friendly.
Open modes
The mode says what you plan to do.
"r" read text
"w" write text (makes a new file or wipes an old one)
"a" append text at the end
"x" create a new file and fail if it already exists
with open is the safe way
Use with open(...) so Python closes the file for you.
Like borrowing a library book and having a helper return it.
Reading a file
read() gets the whole text.
readline() gets one line.
readlines() gets a list of lines.
You can also loop over the file line by line.
Writing and appending
w starts fresh.
a adds to the end and keeps old text.
Check before you trust a path
Files might be missing.
Wrap reads in try/except when the file may not exist.
Paths and tips
Use clear file names.
Know which folder your program runs in.
Text mode is fine for notes. Binary mode is for other data later.
Tip: Use with open so files close even when something goes wrong.
Test yourself
Three quick questions made just for this lesson. Earn 10 XP per correct answer.