Part 08 / Topic 2 of 10
File modes
The second argument of open() is the mode: it says what you want to do, like choosing "read only" or "edit" on a shared document.
Real-world example: a visitor book that keeps old entries.
with open("demo_visitors.txt", "w", encoding="utf-8") as f: # w: start fresh
f.write("Asha\n")
with open("demo_visitors.txt", "a", encoding="utf-8") as f: # a: add to the end
f.write("Ravi\n")
with open("demo_visitors.txt", "r", encoding="utf-8") as f: # r: read
print(f.read().split()) # ['Asha', 'Ravi']
try:
with open("demo_visitors.txt", "x", encoding="utf-8") as f: # x: only if NEW
f.write("Meena\n")
except FileExistsError:
print("Already exists!") # Already exists!
| Mode | Meaning | If file exists | If file is missing |
|---|---|---|---|
"r" |
Read (default) | Reads it | ❌ FileNotFoundError |
"w" |
Write | ⚠️ Empties it first | Creates it |
"a" |
Append | Adds at the end | Creates it |
"x" |
Exclusive create | ❌ FileExistsError |
Creates it |
"rb", "wb" |
Binary read / write | Same as "r" / "w" |
Same as "r" / "w" |
Binary note: for images, PDFs or other non-text files add
b("rb","wb"). You getbytes, notstr, and you do not passencoding.
🔍 Going deeper:
"w"empties the file the moment it is opened, even if you never write anything. To replace an important file safely, write to a temporary file first, then swap it in withPath.replace(). Adding+("r+","a+") opens for reading and writing.
Done here? The practice set for Part 8 — 8 exercises with solutions — is on the part page.