What are the different file modes in Python's `open()` function?
The open() function accepts a mode string that controls how the file is opened:
Basic modes:
'r'-- Read (default). File must exist.'w'-- Write. Creates file or truncates existing file.'a'-- Append. Creates file or appends to existing.'x'-- Exclusive create. Fails if file already exists.
Modifiers (added to basic mode):
'b'-- Binary mode. Data isbytes, notstr.'t'-- Text mode (default). Data isstr.'+'-- Read AND write.
Common combinations:
'rb'-- Read binary (images, audio)'wb'-- Write binary'r+'-- Read/write without truncating'w+'-- Read/write, truncates first'a+'-- Read/append
Additional open() parameters: encoding (default varies by OS, explicitly set to 'utf-8'), newline, buffering, errors.
r = read (must exist)
w = write (truncates!)
a = append (creates if needed)
x = exclusive create (fails if exists)
b = binary mode (bytes)
t = text mode (str, default)
+ = read+write
Always specify encoding='utf-8' for text files
import os
# Write a new file
with open("/tmp/example.txt", "w", encoding="utf-8") as f:
f.write("Hello, World!\n")
f.write("Second line\n")
# Read the file
with open("/tmp/example.txt", "r", encoding="utf-8") as f:
content = f.read()
print(content)
# Append to the file
with open("/tmp/example.txt", "a", encoding="utf-8") as f:
f.write("Appended line\n")
# Exclusive create -- fails if exists
try:
with open("/tmp/example.txt", "x", encoding="utf-8") as f:
f.write("New file")
except FileExistsError:
print("File already exists!")
# Read + Write (without truncating)
with open("/tmp/example.txt", "r+", encoding="utf-8") as f:
content = f.read() # read all
f.seek(0) # go back to start
f.write("MODIFIED") # overwrite beginning
# Binary mode for non-text files
with open("/tmp/data.bin", "wb") as f:
f.write(b"\x00\x01\x02\x03")
with open("/tmp/data.bin", "rb") as f:
data = f.read()
print(data) # b'\x00\x01\x02\x03'
print(type(data)) # <class 'bytes'>
# Always specify encoding for text files
# Bad: open("file.txt") -- encoding depends on OS
# Good: open("file.txt", encoding="utf-8")
# Reading methods
with open("/tmp/example.txt", "r", encoding="utf-8") as f:
all_content = f.read() # entire file as string
f.seek(0)
one_line = f.readline() # one line
f.seek(0)
all_lines = f.readlines() # list of lines
f.seek(0)
for line in f: # iterate line by line (memory efficient)
print(line.rstrip())
# Cleanup
os.remove("/tmp/example.txt")
os.remove("/tmp/data.bin")
- •'w' truncates existing files -- use 'a' to append
- •'x' prevents overwriting existing files
- •Always specify encoding='utf-8' for text files
- •'rb'/'wb' for binary files (images, audio, etc.)
- •'w' mode silently destroys existing file contents!
- •Default encoding varies by OS -- always specify utf-8
- •'r+' requires file to exist; 'w+' creates but truncates
- •Binary mode returns bytes, text mode returns str