Skip to main content

Python Bytes and Bytearray

Data Types Satellite

Bytes & Bytearray

Python treats text (`str`) and binary (`bytes`) separately. Learn how to read/write binary files, encode/decode strings, and mutate buffers.

Encoding & decoding

data = "Python".encode("utf-8")
text = data.decode("utf-8")
  • Always specify encodings when dealing with external systems.
  • Handle errors with errors='ignore' or 'replace' when necessary.

bytes vs bytearray

TypeMutable?When to use
bytesNoImmutable binary data, network responses, file contents
bytearrayYesEfficient mutations, streaming manipulation
buffer = bytearray(b"abc")
buffer[0] = ord("A")

Common operations

  • Read binary files: Path("image.png").read_bytes()
  • Write binary files: Path("copy.bin").write_bytes(data)
  • Slice bytes similar to strings, but results remain bytes.

Next up in your learning path