Interview Prep/Python for DevOps/Exceptions, context managers, files & logging

What file modes exist, and why always pass `encoding`?

BeginnerConceptExceptions, context managers, files & logging
Answer

Modes: r read, w truncate and write, a append, x create and fail if exists, + read/write, b binary. Text mode decodes bytes using encoding; if you omit it, Python uses the locale encoding, which is UTF-8 on most Linux boxes but can be ascii in a minimal container (LANG unset) or cp1252 on Windows. That produces UnicodeDecodeError only in production. Always pass encoding="utf-8" (3.15 makes UTF-8 the default; PYTHONWARNDEFAULTENCODING=1 flags the omissions today).

All Python for DevOps questions Roadmap: Python for automation

More on Exceptions, context managers, files & logging