← Python Programming learning path
Python Programming · Module 9 of 10

Files and errors

Read and write files safely and handle errors with try/except.

📖 Key ideas

  1. open("data.txt") opens a file; mode "r" reads, "w" writes (overwrites), "a" appends.
  2. with open(...) as f: closes the file automatically.
  3. Errors (exceptions) stop a program unless handled.
  4. try/except catches errors; finally always runs.
  5. 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