File modes and context managers
open returns a file object with a selected mode and encoding. r reads, w truncates or creates, and a appends. A with statement closes the handle when its block ends, including during exceptions. Relative paths depend on the working directory; pathlib can express filesystem operations clearly without changing that rule. with open("input.txt",encoding="utf-8") as handle: text=handle.read() explicitly chooses decoding and closes the handle even if processing later raises an exception inside the block. Explicit mode and encoding prevent accidental truncation or platform-dependent text interpretation and make scripts safer to reuse on different operating systems when users supply files containing non-ASCII characters or previously recorded data today. Opening the input in w mode erases it before reading; verify modes and use distinct input and output paths rather than assuming a context manager protects against choosing the wrong operation in the first place.
with open("input.txt",encoding="utf-8") as handle: text=handle.read() explicitly chooses decoding and closes the handle even if processing later raises an exception inside the block.Explicit mode and encoding prevent accidental truncation or platform-dependent text interpretation and make scripts safer to reuse on different operating systems when users supply files containing non-ASCII characters or previously recorded data today.
Opening the input in w mode erases it before reading; verify modes and use distinct input and output paths rather than assuming a context manager protects against choosing the wrong operation in the first place.