Python Glossary Русский

all Python 3sysfunction

sys.getdefaultencoding()

encodings

Returns 'utf-8' — the default encoding of str.encode() and bytes.decode() with no argument. In Python 3 this value never changes.

Syntax

sys.getdefaultencoding()

The main trap: this is NOT the file encoding. Before Python 3.15, open() without encoding uses the locale encoding (locale.getpreferredencoding(), cp1251 on a Russian Windows; UTF-8 since 3.15, PEP 686), so a file read 'by default' can come out as mojibake even though this says utf-8. Python 3 has no setdefaultencoding — pass encoding='utf-8' explicitly.

Examples

import sys
print(sys.getdefaultencoding())  # → utf-8
print('привет'.encode() == 'привет'.encode('utf-8'))  # → True
import locale
print(locale.getpreferredencoding())  # → ? UTF-8 — на Windows cp1251
with open('a.txt', 'w', encoding='utf-8') as f:
    f.write('явно')

See also

Open in the full glossarydocs.python.orgReport an inaccuracy