Python Default Encoding: Six Places to Check in One Process
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.
One string, two byte lengths
Three actions, the same two characters:
| Call | Bytes written | Size |
|---|---|---|
'订单'.encode() | e8aea2e58d95 | 6 B |
open(p, 'w').write('订单') | b6a9b5a5 | 4 B |
open(p, 'wb').write('订单'.encode()) | e8aea2e58d95 | 6 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.
| Call | Returns | What it governs |
|---|---|---|
sys.getdefaultencoding() | utf-8 | str.encode() and bytes.decode() only |
locale.getencoding() | cp936 | The system ANSI code page; ignores UTF-8 mode |
locale.getpreferredencoding() | cp936 | Follows UTF-8 mode; becomes utf-8 when it is on |
open(p) and its .encoding | cp936 | Text file I/O |
sys.stdout.encoding | gbk | stdout, including when redirected to a file or pipe |
sys.getfilesystemencoding() | utf-8 | Filenames, 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:
| Setting | open() default | stdout.encoding | locale.getencoding() | encoding="locale" |
|---|---|---|---|---|
| nothing set | cp936 | gbk | cp936 | cp936 |
-X utf8 or PYTHONUTF8=1 | utf-8 | utf-8 | cp936 | cp936 |
PYTHONIOENCODING=utf-8 alone | cp936 | utf-8 | cp936 | cp936 |
PYTHONUTF8=1 plus -X utf8=0 | cp936 | gbk | cp936 | cp936 |
PYTHONUTF8=0 plus -X utf8 | utf-8 | utf-8 | cp936 | cp936 |
PYTHONUTF8=1 plus PYTHONIOENCODING=gbk | utf-8 | gbk | cp936 | cp936 |
Three usable conclusions:
- The command line beats the environment variable. Rows four and five test both directions, and whichever appears on the command line wins. "I set PYTHONUTF8=1 system-wide" does not tell you what a process will do.
PYTHONIOENCODINGtouches stdio and nothing else. Row three is the clearest case: stdout is already utf-8 while files are still written as cp936. The last row goes further — it drags stdout back to gbk even under UTF-8 mode.- Neither
locale.getencoding()norencoding="locale"moves under UTF-8 mode; both stay at cp936. To learn the machine's real system encoding, askgetencoding(). To reproduce the old behaviour, passencoding="locale".
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.
| Action | Default mode (3.14 and earlier) | UTF-8 mode (3.15 default) |
|---|---|---|
| Write "订单" | 4 B b6a9b5a5 | 6 B e8aea2e58d95 |
| Write a string with an emoji | UnicodeEncodeError | succeeds |
| Write U+20000 | UnicodeEncodeError | succeeds |
| Write the euro sign | UnicodeEncodeError | succeeds |
| Read a GBK file | fine | UnicodeDecodeError |
| Read a UTF-8 file | error or silent mojibake | fine |
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:
- Old default reading a UTF-8 file:
UnicodeDecodeError: 'gbk' codec can't decode byte 0xa7 in position 14: illegal multibyte sequence. Sometimes there is no error at all and you get readable-looking nonsense instead — whether it raises or stays quiet depends on whether those bytes happen to land inside GBK's valid ranges. - UTF-8 mode reading a GBK file:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb6 in position 0: invalid start byte. No ambiguity here; not one character comes out. - Writing text that contains an emoji:
UnicodeEncodeError: 'gbk' codec can't encode character '\U0001f600' in position 2: illegal multibyte sequence.
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:
- Logs and reports your own program writes: they follow the deployment machine, break first, and are the cheapest to fix (write them as utf-8).
- CSV exported from office software: usually GBK, or UTF-8 with a BOM. Always pass
encodingwhen reading. - JSON downloaded from a third-party API: UTF-8 in practice, and therefore the safest of the four.
- Historical archives: the real cost of the migration. Read them with
encoding='gbk', or the widergb18030.
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 site | EncodingWarnings with the switch on |
|---|---|
open(path, 'w') | 1 |
Path.read_text() | 1 |
Path.open('w') | 1 |
json.dump() into a handle with no encoding | 1 |
csv.writer() into a handle with no encoding | 1 |
logging.basicConfig(filename=...) | 1 |
subprocess.run(text=True) | 1 |
io.TextIOWrapper() | 1 |
binary mode open(path, 'wb') | 0 |
encoding='utf-8' or encoding='locale' passed | 0 |
locale.getpreferredencoding() called | 1 |
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.
- Every read of an external file gets an explicit
encoding. Unknown meansutf-8; a known Chinese office export meansgbkorgb18030. - Everything you write goes out as
utf-8. For logging, passlogging.basicConfig(filename=..., encoding='utf-8')— measured, the handler's encoding becomesutf-8and the bytes on disk are UTF-8. - To reproduce the old behaviour temporarily, pass
encoding="locale"(available since 3.10). It returns cp936 even under UTF-8 mode, which rescues old code, but it follows the system, so it changes on the next machine. To pin it, writegbkorutf-8explicitly. - Do not copy the Python 2 idiom
sys.setdefaultencoding('utf-8'). The attribute does not exist in 3.x — measured:AttributeError: module 'sys' has no attribute 'setdefaultencoding'— so the snippet floating around the internet will not even run. - Probe the system encoding with
locale.getencoding(), notgetpreferredencoding(). The latter returnsutf-8under UTF-8 mode, and that drift is exactly why PEP 686 introduced the former.
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:
- Any
open()withoutencodingis code that follows the machine, and cannot be trusted across platforms. str.encode()never needs a second thought about the environment; it is always UTF-8.open()is the one that needs suspicion.- Before migrating, run
-X warn_default_encoding -W error::EncodingWarningto get a complete list of the paths that lean on the default, then decide per site whether to pin the codec or writelocale.
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.