What are the common file modes ('r', 'w', 'a', 'rb') passed to open(), and what does each one do?
Short 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…
Advertisement
AModel 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 stringReal-world example
Using 'a' mode to append new entries to a growing log file without ever overwriting previous entries.
Likely follow-ups
- What happens if you open a file with 'w' mode and the file already contains important data?
Related topics