← Back to Home

Python Default Encoding: Six Places to Check in One Process

python-encodinglocaleutf-8

A CSV file had been running on a Windows machine for three years without a single incident. Nine tenths of it was English column names and timestamps; the last two columns held Chinese status text. Printed as raw bytes, it looked like this:

612c620ab6a9b5a52c310a

The four bytes after a,b\n — b6a9b5a5 — are the word for "order", encoded in GBK. The same two characters in UTF-8 take six bytes: e8aea2e58d95. No line of the codebase mentions encoding, yet the length differs. That is the layer this article takes apart: when you do not pass encoding, which table the interpreter consults, and the fact that this table has already been swapped in Python 3.15.

An earlier piece covered what happens to a bad byte once it arrives — the strict/ignore/replace family of handlers. This one covers the step before that: before a single byte is decoded, something has to decide which codec to use.

// FLOW_01How the default gets decided when encoding is omitted6 NODES01STEP_01the first call passes no encoding02STEP_02check for -X utf8 or PYTHONUTF803STEP_03if set, open as UTF-8, 6 bytes04STEP_04if not, ask locale.getencoding()05STEP_05Windows zh-CN answers cp93606STEP_06the same characters, 4 bytesEND_OF_FLOW
How the default gets decided when encoding is omitted · diagram drawn from this article
Python
Technologies referenced · icons from Simple Icons (CC0)

One string, two byte lengths

Three actions, the same two characters:

CallBytes writtenSize
'订单'.encode()e8aea2e58d956 B
open(p, 'w').write('订单')b6a9b5a54 B
open(p, 'wb').write('订单'.encode())e8aea2e58d956 B

str.encode() defaults to UTF-8 regardless of system language. open() defaults to the locale encoding. Inside one process, two things called "the default" point at two different codecs, and nothing warns you.

The consequence is one file, two ways to read it, two answers:

open(p).read()                  # '订单已发货'
open(p, 'rb').read().decode()   # UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb6 in position 0: invalid start byte

The file is not damaged. The two paths consulted two tables. Whenever a library reads a file fine but open() chokes on it, check this first — it is faster than suspecting corruption.

Six defaults, six answers, one process

Setup: CPython 3.13.14, Windows 11 10.0.26300, Simplified Chinese system locale, PYTHONUTF8 and PYTHONIOENCODING both unset.

CallReturnsWhat it governs
sys.getdefaultencoding()utf-8str.encode() and bytes.decode() only
locale.getencoding()cp936The system ANSI code page; ignores UTF-8 mode
locale.getpreferredencoding()cp936Follows UTF-8 mode; becomes utf-8 when it is on
open(p) and its .encodingcp936Text file I/O
sys.stdout.encodinggbkstdout, including when redirected to a file or pipe
sys.getfilesystemencoding()utf-8Filenames, argv, environment variables

Six rows, three different codec names: utf-8, cp936, gbk. Two of them are the same thing — codecs.lookup('cp936').name returns gbk, and the aliases cp936, gbk and ms936 all normalize to gbk.

That is why one bug reports three different names. The traceback says 'gbk' codec can't encode, the handle says encoding='cp936', and locale.getdefaultlocale() returns ('zh_CN', 'cp936'). Do not treat these as three separate problems.

One more value that misleads: locale.getdefaultlocale() still returns ('zh_CN', 'cp936') under UTF-8 mode (measured). It is inferred from environment variables and the system code page and does not follow UTF-8 mode, so using it as a probe gives you the old answer forever.

Why Chinese filenames never break and Chinese content always does

Because filenames never touch that table. On Windows the filesystem encoding has been UTF-8 since PEP 529, with surrogatepass as the error handler, and neither changed between the two modes: getfilesystemencoding() returned utf-8 in both, and a directory created with a Chinese name round-tripped through listdir intact.

So you end up with a combination that is very good at hiding: the directory is named 订单导出, the filename carries a date, os.listdir() behaves, Path joins behave, and only the file contents are GBK. Anyone testing with a Chinese path walks away convinced encoding is fine, having covered none of the layer that actually breaks.

The boundaries are worth stating plainly. The path layer and the encoding layer share nothing: the path traps (backslashes, case, short names) are covered in eight semantic divergences in Windows paths, and the filesystem error handler (os.fsencode on Windows gives you surrogatepass, not surrogateescape) is covered in five decode error handlers on one round trip. This article stays on the text handle.

Three switches, three scopes, three priorities

Running -X utf8, PYTHONUTF8 and PYTHONIOENCODING against each other produced six rows, all measured on the same machine:

Settingopen() defaultstdout.encodinglocale.getencoding()encoding="locale"
nothing setcp936gbkcp936cp936
-X utf8 or PYTHONUTF8=1utf-8utf-8cp936cp936
PYTHONIOENCODING=utf-8 alonecp936utf-8cp936cp936
PYTHONUTF8=1 plus -X utf8=0cp936gbkcp936cp936
PYTHONUTF8=0 plus -X utf8utf-8utf-8cp936cp936
PYTHONUTF8=1 plus PYTHONIOENCODING=gbkutf-8gbkcp936cp936

Three usable conclusions:

One documented difference I did not measure myself: under UTF-8 mode, sys.stdin and sys.stdout use the surrogateescape error handler while sys.stderr keeps backslashreplace, so the same undecodable byte lands differently in a log than on the terminal.

3.15 has already changed the default

PEP 686 is Final, with Python-Version 3.15. Its specification reads: "Python will enable UTF-8 mode by default from Python 3.15", with an escape hatch: "Users can still disable UTF-8 mode by setting PYTHONUTF8=0 or -X utf8=0". On python.org's download page, 3.15.0 shipped on 2026-10-09 and the latest release at the time of writing is 3.15.2 (2026-10-25).

A scope note first: this machine runs 3.13.14 and has no 3.15 installed, so the data below comes from running 3.13 with PYTHONUTF8=1. That reproduces the code path UTF-8 mode takes; it is not a measurement on the new release. The conclusions hold for that layer only.

ActionDefault mode (3.14 and earlier)UTF-8 mode (3.15 default)
Write "订单"4 B b6a9b5a56 B e8aea2e58d95
Write a string with an emojiUnicodeEncodeErrorsucceeds
Write U+20000UnicodeEncodeErrorsucceeds
Write the euro signUnicodeEncodeErrorsucceeds
Read a GBK filefineUnicodeDecodeError
Read a UTF-8 fileerror or silent mojibakefine

In one sentence: 3.15 fixes the write side and breaks the read side. Under the old default, emoji, rare CJK characters and the euro sign could not be written at all — the traceback reads 'gbk' codec can't encode character '\U0001f600' in position 2: illegal multibyte sequence — and under UTF-8 mode they all go through. But every GBK file ever written with the old default blows up the first time it is read with plain open().

This is loud on Windows because the same code has been fine in Linux containers for years: when the locale is C or POSIX, one of the legacy ASCII locales, the interpreter turns UTF-8 mode on by itself (PEP 540 behaviour, and also when locale coercion fails). "Cannot reproduce locally, green in CI, intermittent mojibake in production" points here.

After the upgrade, yesterday's files do not open

Three directions, three measured tracebacks with completely different symptoms:

PEP 686's Backward Compatibility section states the risk without softening it: the change "may cause UnicodeError, mojibake, or even silent data corruption", and names Windows users as the group most affected.

Sorting by where the files come from changes the priority:

Turn the risk into a failing test with two switches

PEP 597 added EncodingWarning. It is off by default and needs a switch. The combination I use escalates the warning straight into an exception:

python -X warn_default_encoding -W error::EncodingWarning -m pytest

In practice the open() call now raises EncodingWarning: 'encoding' argument not specified with a line number, and the suite goes red instead of printing a warning nobody reads. The equivalent environment variable is PYTHONWARNDEFAULTENCODING=1.

I also measured the coverage by calling each site individually:

Call siteEncodingWarnings with the switch on
open(path, 'w')1
Path.read_text()1
Path.open('w')1
json.dump() into a handle with no encoding1
csv.writer() into a handle with no encoding1
logging.basicConfig(filename=...)1
subprocess.run(text=True)1
io.TextIOWrapper()1
binary mode open(path, 'wb')0
encoding='utf-8' or encoding='locale' passed0
locale.getpreferredencoding() called1

Two notes. Binary mode never warns, because no text codec is involved. And adding -X utf8 changes nothing about which sites fire — all four switch combinations produced identical counts — which tells you it checks whether encoding was written, not whether the code will break. It is a cheap stand-in for static analysis, not a runtime guard. The getpreferredencoding() row is deliberate; PEP 686 asked for it.

Think through the -W error side effect before shipping it: any omitted encoding anywhere in the process becomes a hard failure, including inside third-party libraries, which eventually call open() or TextIOWrapper too. Start with the test suite; do not put it in the production entrypoint.

Migration order: reads first, then writes

Doing it in the other order hurts, because the moment the write side changes, the bytes on disk change while the read side is still expecting the old codec.

Troubleshooting: four tracebacks I actually hit

UnicodeEncodeError: 'gbk' codec can't encode character '\U0001f600' in position 2: illegal multibyte sequence

Write side. Either open(p, 'w') had no encoding, or print() output was redirected into a file. Fix: pass encoding='utf-8' on the handle; for redirected output set PYTHONIOENCODING=utf-8 or add -X utf8.

UnicodeDecodeError: 'gbk' codec can't decode byte 0xa7 in position 14: illegal multibyte sequence

The old default reading a UTF-8 file. Position 14 means the first dozen-odd characters decoded fine and then hit a byte GBK does not accept — which is why this looks like partial corruption. Fix: pass encoding='utf-8' on read.

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb6 in position 0: invalid start byte

The reverse: UTF-8 mode (or a 3.15 default) reading an old GBK file. 0xb6 is the first byte of 订 in GBK. Fix: encoding='gbk', or the wider gb18030 — measured, U+20000 raises under cp936 and encodes to 95328236 under gb18030.

EncodingWarning: 'encoding' argument not specified

Not a fault; you turned the switch on. The line it points at is the one missing encoding. Two fixes: add encoding='utf-8', or, if that site is genuinely meant to follow the system, write encoding='locale' to say so explicitly and the warning stops.

FAQ

Q: I set PYTHONIOENCODING to utf-8, so why are my files still GBK?

Because it only changes stdio. In a process where that variable was the only thing set, sys.stdout.encoding was utf-8 while open(p).encoding remained cp936. To move the file layer, use -X utf8, PYTHONUTF8=1, or pass encoding on each open().

Q: After upgrading to 3.15, can I get open() back to the old behaviour?

Two ways. Globally, PYTHONUTF8=0 or -X utf8=0 — but those are read at interpreter startup and cannot be changed at runtime. Per call site, encoding="locale", which still yields cp936 under UTF-8 mode (measured). The second is the better fit for a gradual migration.

Q: Why does the same program work in Docker and produce mojibake on Windows?

The container usually runs under the C or POSIX locale, where the interpreter enables UTF-8 mode automatically and open() defaults to utf-8. A Chinese Windows install answers cp936. Same code, two defaults, nobody typed anything wrong, different results.

Q: My Chinese filenames have always been fine, does not that mean my encoding handling is correct?

No. Filenames use the filesystem encoding, which is UTF-8 on Windows; file contents use the locale encoding. The two layers do not share a table. I created Chinese directories under both modes and listdir returned them intact, in the same process where the default for file contents moved from cp936 to utf-8. Testing via Chinese paths covers none of the layer that breaks.

Closing

Three checks worth pasting into code review:

As for that three-year-old CSV: nothing is wrong with it. It has simply never been read under UTF-8 mode, and 3.15 will tell you so at the first open(). If you want the next layer down — what five different handlers do to a bad byte once it arrives — continue with five decode error handlers, one round trip. For the pipe layer (subprocess with text=True returning an empty string while the exit code says zero), seven silent subprocess failures has the measurements, and CSV record boundaries are in eight boundaries your CSV reader silently moves.

👉 Join Xiaomi MiMo Platform: Leading AI model platform with cost-effective inference

👉 Join Aliyun AI: Top AI products with exclusive coupons for business innovation

📌 This article was AI-assisted generated and human-reviewed | TechPassive — An AI-driven content testing site focused on real tool reviews

🔗 Recommended Tools

These are carefully selected tools. Using our affiliate links supports us to keep producing quality content:

As an Amazon Associate, I earn from qualifying purchases at no extra cost to you.

☁️ DigitalOcean Cloud ⚡ Vultr VPS 🤖 QoderWork CN (Refer & Earn) ☁️ Aliyun AI Products 📚 WordPress Books 🧠 AI & LLM Books 🏗️ System Design Books 🐳 Docker & K8s Books 🐧 Linux Admin Books 🐍 Python Books 🗄️ Database Books 🚀 DevOps & SRE Books 🤖 Xiaomi MiMo Platform
← Back to Home