Python os.fsencode() – Encodes the specified file name to the file system encoding

Python os.fsencode()

The Python os.fsencode() method is used to encode the specified file name to the file system encoding, using the “surrogateescape” error handler or “strict” on Windows;

Syntax: os.fsencode(filename)

Parameters:

filename: A path-like object representing a file system path. A path-like object is a str or bytes object representing the path.

Return type: This method returns a bytes string representing the encoded file name.

Example 1

Use the os.fsencode() method

# Python program to explain os.fsencode() method
    
# importing os module
import os
  
#Filename
filename = "/home/user/File.txt"
  
# Encode the filename
# to the filesystem encoding
# with 'surrogateescape' error handler,
# or 'strict' (On Windows)
encode = os.fsencode(filename)
  
#Print the encoded filename
print(encode)
  
# The encode filename can be
# decoded using os.fsdecode() method
print(os.fsdecode(encode))

Output:

Encoded filename: b'/home/user/Fxc3x8exe2x95x9axc3x88.txt'
/home/user/FÎ?È.txt

Leave a Reply

Your email address will not be published. Required fields are marked *