PyPython · Lesson 10 of 14
File I/O
Python file handling is clean and safe with the "with" statement, which automatically closes files even if an exception occurs. It is a small thing that prevents a large number of subtle bugs.
⚠ Warning
Always use "with open(...) as f:" — never bare open() without a close(). The with statement guarantees the file is closed even if an exception is raised inside the block. Also: "w" mode truncates the file immediately on open, before you write anything.
Always use "with open(...) as f:" — never bare open() without a close(). The with statement guarantees the file is closed even if an exception is raised inside the block. Also: "w" mode truncates the file immediately on open, before you write anything.