Lesson 17: Writing files & with
Last lesson we read files; now we'll write to them. You open a file in write mode with open("file.txt", "w") and write with .write(). The clean way is with: with open("file.txt", "w") as f: — which closes the file automatically at the end of the block. Note: mode "w" starts from an empty file — any
with open(...) as f: is like opening a notebook, writing, and having someone close it automatically when you're done. Mode "w" starts from a blank page.
- .write()
- .write(text) writes a string to a file opened in write mode.
- with statement
- with open(...) as f: opens a file and closes it automatically at the end of the block.
- write mode "w"
- Mode "w" opens a file for writing — it creates a new file or erases existing content.