Working with Files
Programs are more useful when they can save data between runs. Python's built-in open() reads and writes files.
Pythonshares state with other Python blocks
The with statement
with open(...) as f: opens the file and guarantees it gets closed automatically when the block ends, even if an error happens inside it. Without with, you'd have to remember to call f.close() yourself.
Common modes
| Mode | Meaning |
|---|---|
"r" | Read (default), errors if the file doesn't exist |
"w" | Write, creates the file or overwrites it completely |
"a" | Append, adds to the end without erasing existing content |