← Python Programming learning pathPython Programming · Module 9 of 10
Files and errors
Read and write files safely and handle errors with try/except.
📖 Key ideas
- open("data.txt") opens a file; mode "r" reads, "w" writes (overwrites), "a" appends.
- with open(...) as f: closes the file automatically.
- Errors (exceptions) stop a program unless handled.
- try/except catches errors; finally always runs.
- Common errors: ValueError, TypeError, FileNotFoundError, ZeroDivisionError.
💡 Real-life example: try/except is like a seat belt: you hope not to need it, but it saves you when something goes wrong.
with openOpens a file and closes it automatically
"a" modeAdds to the end of a file
try/exceptCatches errors
FileNotFoundErrorRaised when a file is missing