Walkthrough: Write Then Read
例题: 写入再读取
Three tiny functions — write a file, read it back as a string, read it as a list of lines. The `with` statement guarantees the file gets closed.
The three functions
Python · runnable
Three modes
| Mode | Effect on existing file | Use case |
|---|---|---|
"r" | (default) read-only, opens at start | Read existing data |
"w" | erases then writes | Overwrite outputs |
"a" | appends to the end | Logs, audit trails |