all Python 3localefunction
locale.getpreferredencoding()
encoding
Returns the encoding open() uses for text files without encoding=; in UTF-8 mode it is always 'utf-8'.
Syntax
locale.getpreferredencoding(do_setlocale=True)
This is where 'on Windows the file opened as cp1251' comes from: without encoding=, open() asks this function, so one program reads the same file differently on different machines. Since 3.15 UTF-8 mode is on by default and the answer became 'utf-8', yet an explicit encoding='utf-8' remains the only portable choice. The default do_setlocale=True may call setlocale() temporarily, which is not thread-safe, so pass False.
Examples
import locale
print(locale.getpreferredencoding(False)) # → ? utf-8 или cp1251 — зависит от машины
with open('note.txt', 'w', encoding='utf-8') as f: # явная кодировка не зависит от машины
f.write('привет')
with open('note.txt', encoding='utf-8') as f:
print(f.read()) # → привет
See also
Open in the full glossarydocs.python.orgReport an inaccuracy