python type_error ai_generated true

TypeError: a bytes-like object is required, not 'str'

ID: python/typeerror-expected-str-got-bytes

Also available as: JSON · Markdown
95%Fix Rate
95%Confidence
50Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
311 active

Root Cause

Mixing str and bytes. Common when reading files in binary mode or working with network data.

generic

Workarounds

  1. 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

  2. 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

  3. 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:

  1. Open file without 'b' mode to avoid bytes 65% fail

    May corrupt binary data or fail on non-text files

  2. Use str() to convert bytes 80% fail

    str(b'data') gives "b'data'" not "data" — use .decode()

Error Chain

Frequently confused with: