Writing files and the with statement
18-minute lesson · module-files-03
You are previewing this course as a guest
Read anything and run any exercise you like. It all runs in your own browser, so nothing here is saved: no XP, no progress, and the AI tutor needs an account. Sign in and your work starts counting.
Writing files and the with statement
18-minute lesson · module-files-03
- Write text to a file with `.write()` in write mode.
- Add lines without erasing existing content using append mode.
- Build formatted output lines with f-strings or `.format`.
- Verify written output by reading the file back.
Source attribution
Status: adapted
How to Think Like a Computer Scientist: Interactive Edition — source · Files / Writing Text Files / With Statements
Adaptation notes. Reading rewritten in our voice. The grade-report example is ours. The coding exercise writes to a /tmp path and the test reads the file back to verify, so it runs identically in Pyodide and a local subprocess.
License notes. Original chapter is GNU FDL 1.3 (Brad Miller, David Ranum, and the upstream Elkner/Downey/Meyers text). No verbatim text reproduced.