liveBook · Manning

UTF-8

As explained in Python Workout: 50 ten-minute exercises

UTF-8 is a variable-width Unicode character encoding that represents characters using one to four eight-bit code units.

When Python reads ordinary text, its strings contain Unicode characters encoded in UTF-8. UTF-8 converts Unicode code points into bytes using a variable number of bytes: ASCII characters use one byte, while many other scripts and emoji use two or more. This makes multilingual text practical, but requires care when translating between bytes and characters. section 2.0 section 2.18

Text files versus binary files

Opening a PDF or JPEG as ordinary text makes Python expect valid UTF-8 and can raise an exception. Open such files with binary mode, using a mode such as 'rb', then read fixed-size byte chunks rather than treating the data as lines. section 5.2

with open(filename, 'rb') as f:     #1
    while True:
        one_chunk = f.read(1000)    #2
        if not one_chunk:
            break
        print(f'This chunk contains {len(one_chunk)} bytes')

A fixed-size binary-reading loop stops when read returns no bytes and reports the byte count of each chunk. section 5.2

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Defines code points, byte widths, and ASCII compatibility, then applies the bytes-versus-characters distinction to file handling.
Examples
Uses multilingual scripts, emoji, PDFs, JPEGs, binary mode, and fixed-size byte chunks as concrete cases.
What you can do after
Operate/configure Python file reads by selecting text or binary mode and consuming binary data in fixed-size chunks.
How it connects
Connects Unicode, ASCII, Python strings, bytes, and file modes.

Also explained in

Compare how 11 books explain UTF-8 →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout: 50 ten-minute exercises. The section links point to the parts of the book it draws on.