EncodingWarning
PythonWARNINGCommonWarning

Locale or encoding mismatch detected

Quick Answer

Always pass encoding="utf-8" explicitly to open() and other I/O functions.

Production Risk

Low.

What this means

Raised (Python 3.10+) when the encoding used for a file or text operation is locale-dependent and may not be what was intended. Triggered when opening files without an explicit encoding= argument in a UTF-8-unaware locale.

Why it happens
  1. 1open() called without encoding= argument when PYTHONWARNDEFAULTENCODING=1
  2. 2Platform default encoding differs from the file's actual encoding

Fix

Specify encoding explicitly

Specify encoding explicitly
# Bad — locale-dependent
with open('data.txt') as f: ...

# Good
with open('data.txt', encoding='utf-8') as f: ...

Why this works

Explicit encoding= removes the locale dependency and ensures consistent behaviour across platforms.

Code examples
Enable the warningpython
import warnings
warnings.filterwarnings('error', category=EncodingWarning)
open('f.txt')  # raises EncodingWarning if encoding omitted
Suppress per-callpython
import io
with io.open('f.txt', encoding='utf-8') as f:
    data = f.read()
Same error in other languages
Sources
Official documentation ↗

Python 3.10+ — PEP 597

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Python errors