Reading and writing files in Python
File IO with with: open, use, and auto-close.
with open("notes.txt", "w") as f:
f.write("first line\n")
f.write("second line\n")
with open("notes.txt") as f:
contents = f.read()
with open("notes.txt") as f:
lines = [line.rstrip() for line in f]
with open("notes.txt", "a") as f:
f.write("appended\n")
How it works
- Mode
"w"writes fresh;"a"appends. readslurps everything; iterating yields lines.- The
withblock closes the file even on errors.
Keywords and builtins used here
asforopenwith
The run, in numbers
- Lines
- 12
- Characters to type
- 257
- Tokens
- 95
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 57 seconds.
Step 6 of 7 in Iterators, errors & files, step 49 of 72 in Language basics.