File Handling

Lesson 20 of 20

Open, write and read text files — and see why the with statement closes every file for you, every time.

The big picture

Files: data that outlives the program

open() hands you a handle to a file on disk; write and read move text through it, and with makes sure it is always closed.

Handles, Not Files

open() gives you a handle — a remote control aimed at a file on disk.

Modes Matter

"w" wipes, "a" appends, "r" reads — the mode letter decides the superpowers.

with = No Leaks

The with statement closes the file the instant its block ends — even on errors.

Text In, Text Out

write() sends strings; read() returns one big string with \n markers inside.