Opening a Text File with an Explicit Encoding

Opening a file as text asks the runtime to decode bytes. Choosing the encoding explicitly makes the result independent of many environment defaults.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Use the format's declared encoding
  2. Handle a bad input file
  3. Decode bytes using the encoding in the file contract
  4. Tell decoders and parsers which errors they each own

Use the format's declared encoding

For a UTF-8 report containing café, decode bytes using UTF-8 and compare the resulting text with the expected spelling. Encoding and decoding explain how the bytes determine that result.

Handle a bad input file

An older file may use a different encoding or contain corrupted bytes. The reader can give a useful diagnostic or handle the documented fallback. Decoding error policies identify which information survives that decision.[1]

Decode bytes using the encoding in the file contract

The byte sequence C3 A9 0A represents é and a newline in UTF-8. Reading it as Latin-1 yields two characters before the newline. An explicitly configured UTF-8 reader gives the same interpretation across environments that choose different defaults. See encoding round trips.

Bytes C3 A9 0A
UTF-8 → é plus logical newline
Latin-1 → U+00C3 and U+00A9 plus newline

Tell decoders and parsers which errors they each own

A malformed byte sequence is an encoding problem. A valid line lacking a required field is a parse problem. Test one of each and preserve useful input locations. Specify newline handling if exact line terminators are required.

References

  1. Python Software Foundation, io: Core Tools for Working with Streams ↩