Interview Q&A / Python

BeginnerQuick answer1 min readUpdated 3 Oct 2026

What are the common file modes in Python's open() function?

SHORT ANSWER

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

python
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 exists

Use "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."

#python#file-io

Related questions

Practise more Python questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Python quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.