Concept
Working with Raw Bytes & Binary Files (`"rb"`, `"wb"`)
Binary files (images, audio, zip archives) cannot be read as text strings. Open with `"rb"` or `"wb"` to read or write immutable `bytes` objects.
python
raw_bytes = b"PNG\r\n\x1a\n"
print(type(raw_bytes)) # <class 'bytes'>
print(raw_bytes[0]) # 80 (ASCII byte value for 'P')
# 19. Working with Raw Bytes & Binary Files (`"rb"`, `"wb"`) Binary files (images, audio, zip archives) cannot be read as text strings. Open with `"rb"` or `"wb"` to read or write immutable `bytes` objects: ```python raw_bytes = b"PNG\r\n\x1a\n" print(type(raw_bytes)) # <class 'bytes'> print(raw_bytes[0]) # 80 (ASCII byte value for 'P') ``` Text files are decoded into Unicode character strings (`str`). Binary mode disables Unicode decoders entirely, handing you raw integers between `0` and `255` representing physical bits on disk.
Checkpoint
What prefix denotes a raw byte literal in Python?
Practice
Create a `bytes` literal `b"DATA"`. Convert it to a plain string using `.decode("utf-8")` and print it.
01
Tap code blocks below to assemble
Available Blocks