SyntaxStudy
Sign Up
Python File Modes & Encoding
Python Intermediate 9 min read

File Modes & Encoding

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 chars

Seeking

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)
Example
import io

# In-memory text file (no disk I/O)
buf = io.StringIO()
buf.write("Hello
")
buf.write("World
")
buf.seek(0)
print(buf.read())

# In-memory binary file
bbuf = io.BytesIO()
bbuf.write(b"\x89PNG\r
")
bbuf.seek(0)
print(bbuf.read(4))  # b'\x89PNG'
Pro Tip

On Windows, text mode translates \n to \r\n on write and back on read. Open in binary mode ("rb"/"wb") when you need byte-for-byte accuracy.