Python › File I/O & Context Managers

What are the common file modes ('r', 'w', 'a', 'rb') passed to open(), and what does each one do?

Beginner

Answer

'r' opens for reading (default, error if the file doesn't exist); 'w' opens for writing, TRUNCATING (erasing) any existing content; 'a' opens for APPENDING to the end without erasing existing content; adding 'b' to any mode (like 'rb') opens the file in BINARY mode, returning bytes instead of decoded text strings.
with open("log.txt", "a") as f:
    f.write("New log entry\n")  # appends, doesn't erase existing content

with open("image.png", "rb") as f:
    data = f.read()  # returns bytes, not a decoded string
Real-world example Using 'a' mode to append new entries to a growing log file without ever overwriting previous entries.

Common follow-ups: What happens if you open a file with 'w' mode and the file already contains important data?