What are the common file modes in Python's open() function?
r" reads (default), "w" writes and erases existing content, "a" appends to the end, and "x" creates a new file and fails if it exists. Adding "+" allows both read and write, and "b" means binary instead of text.
Explain it simply
Think of a diary. "r" means you only read it. "w" means you tear out all the old pages and start fresh, which is dangerous if you opened the wrong diary. "a" means you add new entries at the end. "x" means you buy a brand-new diary and refuse if one already exists.
Example
with open("notes.txt", "w", encoding="utf-8") as f:
f.write("line 1\n")
with open("notes.txt", "a", encoding="utf-8") as f:
f.write("line 2\n")
with open("notes.txt", "r", encoding="utf-8") as f:
print(f.read())
# Output: line 1
# Output: line 2
# Output:
try:
open("notes.txt", "x")
except FileExistsError:
print("already exists") # Output: already existsUse "rb" and "wb" for images, PDFs and other non-text files, and pass encoding="utf-8" for text so behaviour does not depend on the operating system's default.
What to say in the interview
"r reads, w truncates and writes, a appends, x creates exclusively, + adds the other direction, and b switches to bytes. Opening with w erases existing content, so I choose the mode carefully. I always give an explicit encoding for text files and open with a with statement."