← All lessons

Encodings: utf-8

Sign in · Sign up

Lesson 9.8

An encoding says how characters turn into bytes. For any text outside plain English, choose utf-8 both when writing and when reading:

with open("rus.txt", "w", encoding="utf-8") as f:
    f.write("Hello, world!\n")

with open("rus.txt", encoding="utf-8") as f:
    print(f.read())

If you write in utf-8 but read without naming the encoding, on Windows you may get an error or garbled text — that system does not default to utf-8.

The check sets the file name filename and the text text with letters beyond plain English. Write the text to the file in utf-8, then read the file as bytes with "rb", decode them as utf-8 and print the result. It is the same as read_text, but you can see how the bytes work.

Hint

Write as text, read as bytes: "w" with encoding="utf-8", then "rb".

raw.decode("utf-8") turns the bytes back into text. len(raw) counts bytes, not letters: a non-English letter takes more than one.