Python | os.fsencode() method

OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.

os.fsencode() method in Python is used to encode the specified filename to the filesystem encoding with ‘surrogateescape‘ error handler, or ‘strict‘ on Windows;

Syntax: os.fsencode(filename)



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

Return Type: This method returns a bytestring which represents the encoded filename.

Code: use of os.fsencode() method

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output:

Encoded filename: b'/home/user/F\xc3\x8e\xe2\x95\x9a\xc3\x88.txt'
/home/user/FÎ?È.txt

Reference: https://docs.python.org/3/library/os.html#os.fsencode



My Personal Notes arrow_drop_up

self motivated and passionate programmer

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.