Python Glossary Русский

Python 3.2+osfunction

os.fsencode

os — path encoding

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

Syntax

os.fsencode(filename)

It uses the filesystem encoding with the surrogateescape handler, so a name read as str with undecodable bytes turns back into the original bytes losslessly. bytes pass through unchanged. Use it when a system call or external library accepts paths only as bytes.

Examples

import os
import pathlib
print(os.fsencode('abc'))   # → b'abc'
print(os.fsencode(b'abc'))   # → b'abc'
print(os.fsencode('данные.txt'))   # → b'\xd0\xb4\xd0\xb0\xd0\xbd\xd0\xbd\xd1\x8b\xd0\xb5.txt'
print(os.fsencode(pathlib.PurePosixPath('/tmp/data.txt')))   # → b'/tmp/data.txt'
print(os.fsdecode(os.fsencode('данные.txt')))   # → данные.txt

See also

Open in the full glossarydocs.python.orgReport an inaccuracy