Python Glossary Русский

Python 3.2+osfunction

os.fsdecode

os — path encoding

Decode a path (bytes) to str using the filesystem encoding.

Syntax

os.fsdecode(filename)

Undecodable bytes raise no error but become surrogate characters: such a string works for reopening the file, yet printing it or writing it as UTF-8 raises UnicodeEncodeError. For display repr() or decode with errors='replace' is safer. str passes through unchanged.

Examples

import os
print(os.fsdecode(b'abc'))   # → abc
print(os.fsdecode('abc'))   # → abc
print(os.fsdecode(b'\xd0\xb4\xd0\xb0\xd0\xbd\xd0\xbd\xd1\x8b\xd0\xb5.txt'))   # → данные.txt
print(sorted(os.fsdecode(n) for n in os.listdir(b'.')))   # → имена файлов текущего каталога как str, например ['data.txt', 'main.py']
print(os.fsdecode(5))   # → TypeError: expected str, bytes or os.PathLike object, not int

See also

Open in the full glossarydocs.python.orgReport an inaccuracy