python
type_error
ai_generated
true
TypeError: a bytes-like object is required, not 'str'
ID: python/typeerror-expected-str-got-bytes
95%Fix Rate
95%Confidence
50Evidence
2023-01-01First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 311 | active | — | — | — |
Root Cause
Mixing str and bytes. Common when reading files in binary mode or working with network data.
genericWorkarounds
-
95% success Encode strings to bytes: text.encode('utf-8')
text.encode('utf-8')Sources: https://docs.python.org/3/library/stdtypes.html#str.encode
-
95% success Or decode bytes to string: data.decode('utf-8')
data.decode('utf-8')Sources: https://docs.python.org/3/library/stdtypes.html#bytes.decode
-
90% success Open files in text mode ('r') for text, binary mode ('rb') for binary data
# Text mode for text files: with open('file.txt', 'r', encoding='utf-8') as f: ... # Binary mode for images/archives: with open('file.bin', 'rb') as f: ...Sources: https://docs.python.org/3/library/functions.html#open
Dead Ends
Common approaches that don't work:
-
Open file without 'b' mode to avoid bytes
65% fail
May corrupt binary data or fail on non-text files
-
Use str() to convert bytes
80% fail
str(b'data') gives "b'data'" not "data" — use .decode()
Error Chain
Frequently confused with: