Python Glossary Русский

Python 3.6+sysfunction

sys.getfilesystemencodeerrors()

encodings

Returns the error handler for file names: 'surrogateescape' on Linux and macOS, 'surrogatepass' on Windows.

Syntax

sys.getfilesystemencodeerrors()

On Linux a file name is any bytes, not necessarily valid UTF-8. Python hides such bytes as surrogates like \udcff, so os.listdir() does not fail. But a string holding them cannot be printed or written as UTF-8 — you get UnicodeEncodeError 'surrogates not allowed'. os.fsencode() (or encode with the same 'surrogateescape' handler) turns it back into the original bytes, a plain encode('utf-8') does not.

Examples

import sys
print(sys.getfilesystemencodeerrors())  # → ? surrogateescape — на Windows surrogatepass
import os, sys
if sys.getfilesystemencodeerrors() == 'surrogateescape':
    name = os.fsdecode(b'report\xff.txt')
    print(ascii(name))  # → 'report\udcff.txt'
    try:
        name.encode('utf-8')
    except UnicodeEncodeError as e:
        print(e.reason)  # → surrogates not allowed
    print(os.fsencode(name))  # → b'report\xff.txt'

See also

Open in the full glossarydocs.python.orgReport an inaccuracy