liveBook · Manning

Binary data

As explained in The Quick Python Book, Fourth Edition

Binary data is information represented as encoded bytes rather than directly as human-readable text characters.

Binary data represents information as encoded bytes rather than directly as human-readable text characters. Python handles it with bytes objects and binary file modes such as rb and wb. section 13.0 section 6.9

Use binary data when:

  • A file is generated or consumed by another program and follows a defined binary format. section 13.7
  • A Path object should read or write bytes directly through read_bytes and write_bytes. section 13.5
  • A string must cross the text boundary: encode converts it to bytes, while decode converts bytes back to a string. section 6.9

Bytes may look like strings, but they are a different type and cannot be combined directly with strings. For structured records, struct format strings describe fields, pack writes them as bytes, and unpack restores values. section 13.7 section 6.9

Writing and reading a structured record

The format 'hd7s' describes a short integer, a double-precision float, and seven characters. struct.pack('hd7s', 42, 3.14, b'goodbye') creates one record. Reading record-sized chunks and applying struct.unpack produces [(42, 3.14, b'goodbye')].

from pathlib import Path
p_text = Path('my_text_file')
p_text.write_text('Text file contents')
 
18                                             #1
 
p_text.read_text()
 
'Text file contents'
 
p_binary = Path('my_binary_file')
p_binary.write_bytes(b'Binary file contents')
 
20                                             #1
 
p_binary.read_bytes()
 
b'Binary file contents'                        #2
#1 Number of bytes written
#2 Data as bytes

Compare text and binary Path operations: write_text/read_text use strings, while write_bytes/read_bytes use bytes and replace existing content rather than append. section 13.5

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains bytes, binary modes, pathlib methods, and structured packing, while recommending higher-level object storage for many custom formats.
Examples
Uses pathlib byte I/O, encoded accented text, and C-compatible records containing an integer, float, and character sequence.
What it assumes
Assumes general programming knowledge, while establishing the distinction between Unicode strings and bytes.
What you can do after
Apply it via pathlib or struct to write, read, pack, and unpack binary files.
How it connects
Connects binary data with bytes, text files, pathlib, the struct module, encoding, decoding, and pickling.

Also explained in

Compare how 4 books explain binary data →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.