File modes in Python
Read, write, append, exclusive and binary — and what each one destroys.
from pathlib import Path
path = Path("modes.txt")
path.write_text("first\n", encoding="utf-8")
with open(path, "a", encoding="utf-8") as f:
f.write("second\n")
with open(path, encoding="utf-8") as f:
print(f.read().splitlines())
with open(path, "rb") as f:
print(f.read()[:6])
try:
open(path, "x")
except FileExistsError:
print("x refuses to clobber")
How it works
wtruncates;aappends;xrefuses if the file exists.bgives bytes instead of text, with no newline translation.encodingshould be explicit whenever text crosses machines.
Keywords and builtins used here
asexceptopenprinttrywith
The run, in numbers
- Lines
- 18
- Characters to type
- 356
- Tokens
- 123
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 74 seconds.
Step 3 of 3 in Errors in depth, step 64 of 72 in Language basics.