Working with the filesystem.
THE BASIC PATTERN
Open a file, work with it, close it.
WHAT TO USE
The construct that closes the file automatically when you finish.
WHY
Files left open cause problems, particularly in long-running programs.
READING MODES
Read the whole file at once Read line by line
WHICH TO USE
Line by line, for anything large.
Reading a large file entirely into memory is a common cause of failure.
WRITING MODES
Overwrite, which discards existing content Append, which adds to the end
THAT DISTINCTION
Opening for writing destroys the existing contents immediately.
Be certain which you intend.
ENCODING
Always specify it explicitly.
Defaults differ between systems, which produces failures that appear only elsewhere.
WHAT TO USE UNLESS YOU HAVE A REASON OTHERWISE
The common international encoding.
WHAT TO CHECK
That the file exists before reading That you have permission to write
WHAT TO HANDLE
Missing files and permission errors, explicitly.