Text Files · 6 / 17 Theory

Text encodings: UTF-8 and Latin-1

A file stores bytes, not letters. An encoding is the table that says which bytes represent which characters. If you read with a different one from the one used to write, you will see strange symbols (ñ) or an error.

t = "café"
print(len(t), len(t.encode("utf-8")), len(t.encode("latin-1")))   # 4 5 4
print(t.encode("utf-8"))                       # b'caf\xc3\xa9'
print(b"caf\xc3\xa9".decode("utf-8"))           # café
print(b"caf\xe9".decode("latin-1"))             # café

try:
    b"caf\xe9".decode("utf-8")
except UnicodeDecodeError as e:
    print(e.reason)                            # invalid continuation byte

print(b"caf\xe9".decode("utf-8", errors="replace"))   # caf� (the replacement character)
print("日本".encode("latin-1", errors="replace"))      # b'??'
print("€ ok".encode("ascii", errors="ignore"))         # b' ok'

with open("demo.txt", "w", encoding="utf-8") as f:
    f.write("ñ")
print(open("demo.txt", "rb").read())                   # b'\xc3\xb1'
print(open("demo.txt", encoding="latin-1").read())     # ñ   (wrongly decoded)

with open("bom.txt", "w", encoding="utf-8-sig") as f:  # UTF-8 with a BOM mark (Excel)
    f.write("hello")
print(open("bom.txt", "rb").read()[:3])                # b'\xef\xbb\xbf'
  • UTF-8 is the current standard: any Unicode character, from 1 to 4 bytes (accented letters take 2). Latin-1 uses 1 byte per character but only covers 256 characters.
  • Always state the encoding when opening: open(path, encoding="utf-8"). If you do not, Python uses the system one, which changes from one computer to another.
  • errors="replace" and errors="ignore" avoid the exception, but lose data: use them consciously.
  • utf-8-sig reads and writes UTF-8 with the BOM mark that some programs add (for example Excel).
  • If you do not know a file's encoding, try UTF-8 first: it is very rare for text in another encoding to be valid UTF-8 by chance.

You practice it in Characters and bytes and Read a file of unknown encoding.