Open the file in text mode ("r", "w", or "a" with encoding="utf-8") instead of binary mode ("rb", "wb", "ab"), or encode/decode strings explicitly using .encode("utf-8") and .decode("utf-8") when binary mode is required—because Python 3 strictly separates bytes (raw binary data) from str (Unicode text).
Basic Example
# WRONG: Opening in binary mode ('wb' / 'rb') and passing/comparing a 'str'
# with open("data.txt", "wb") as f:
# f.write("Hello, world!\n") # Raises TypeError: a bytes-like object is required, not 'str'
# 1. FIX A (Recommended for text): Open in text mode ('w' / 'r') with explicit UTF-8 encoding
with open("data.txt", "w", encoding="utf-8") as file:
file.write("Hello, world!\n")
with open("data.txt", "r", encoding="utf-8") as file:
for line in file:
if "Hello" in line: # Both 'Hello' and 'line' are str
print(line.strip())
# 2. FIX B (When binary mode is required): Prefix literals with b"" or call .encode('utf-8')
with open("data.bin", "wb") as file:
file.write(b"Header bytes\n")
file.write("Dynamic text\n".encode("utf-8"))
Common File Scenarios & Targeted Fixes
- 1. Writing
strto a file opened with"wb"or"ab": Passing"wb"tells Python the file stream accepts onlybytes,bytearray, ormemoryview. Change the mode to"w"/"a"withencoding="utf-8", or calltext.encode("utf-8")before writing. - 2. Searching or splitting lines read from a
"rb"file (if "keyword" in line:orline.split(",")): Reading a file opened with"rb"yieldsbytesobjects (b"..."). Performingstroperations on those lines—such as"error" in line,line.split(","), orre.search(r"pattern", line)—raisesTypeError: a bytes-like object is required, not 'str'.- Fix: Either open the file in text mode (
"r",encoding="utf-8"), decode each chunk (line.decode("utf-8")), or use byte literals (b"error" in line,line.split(b",")).
- Fix: Either open the file in text mode (
- 3. Using
csv.writer/csv.readerwith binary mode: In Python 2, CSV files were opened in binary mode ("wb"/"rb"). In Python 3, thecsvmodule operates exclusively on text streams—always open CSV files in text mode withnewline="":import csv with open("output.csv", "w", newline="", encoding="utf-8") as file: writer = csv.writer(file) writer.writerow(["name", "score"]) - 4. Passing strings to
subprocess,socket,gzip, orhashlibfile-like APIs: Modules likegzip.open("file.gz", "wb"),hashlib.sha256(), andsubprocess.Popen(..., stdin=PIPE)default to binary streams (bytes). Forgzip, pass text mode"wt"or"rt"withencoding="utf-8"(gzip.open("file.gz", "wt", encoding="utf-8")) to read and writestrdirectly. - 5.
pathlib.Path.write_bytes()vs.Path.write_text(): CallingPath("file.txt").write_bytes("hello")raises the sameTypeError; usePath("file.txt").write_text("hello", encoding="utf-8")for strings orPath("file.bin").write_bytes(b"hello")for raw bytes.
File Mode & Data Type Reference
| File Mode / API | Stream Data Type | Valid Input / Comparison Type | Fix When TypeError Occurs |
|---|---|---|---|
open(p, "w", encoding="utf-8") |
Text (str) |
str ("abc") |
Use for all plain-text, JSON, CSV, and log files. |
open(p, "wb") / open(p, "rb") |
Binary (bytes) |
bytes (b"abc") |
Switch to "w"/"r" for text, or encode/decode with .encode("utf-8") / .decode("utf-8"). |
csv.reader / csv.writer |
Text (str) |
str with newline="" |
Replace "rb"/"wb" with open(p, "r", newline="", encoding="utf-8"). |
gzip.open(p, "wt", encoding="utf-8") |
Text (str) |
str ("abc") |
Use "wt" / "rt" instead of default "wb" / "rb" when compressing text. |
Path.write_text() / Path.read_text() |
Text (str) |
str ("abc") |
Replace write_bytes() / read_bytes() when working with strings. |
You must log in or register to comment.
