File Modes & Encoding
The mode string controls how a file is opened. Choosing the right encoding avoids corrupted data and cross-platform bugs.
Mode Reference
"""
Mode | Description
------+---------------------------
r | Read (default). File must exist.
w | Write. Creates or truncates.
a | Append. Creates if needed.
x | Exclusive create. Fails if exists.
b | Binary (combine: rb, wb, ab)
t | Text (default, combine: rt, wt)
+ | Read+Write (r+, w+, a+)
"""Text vs Binary
# Text mode: newline translation, encoding/decoding
with open("text.txt", "rt", encoding="utf-8") as f:
print(f.read())
# Binary: raw bytes, no translation
with open("image.png", "rb") as f:
data = f.read()Encoding
import locale
print(locale.getpreferredencoding()) # system default
# Always be explicit:
with open("file.txt", "w", encoding="utf-8") as f:
f.write("Héllo Wörld")
with open("file.txt", "r", encoding="utf-8") as f:
print(f.read())
# Error handling
with open("file.txt", "r", encoding="ascii", errors="replace") as f:
print(f.read()) # ? for undecodable charsSeeking
with open("data.txt", "r+", encoding="utf-8") as f:
f.seek(0, 2) # seek to end
size = f.tell() # file size in bytes
f.seek(0) # back to beginning
first_char = f.read(1)