Python os.fsencode() Method

Python os.fsencode() Method

  1. Syntax of Python os.fsencode() Method
  2. Example Code: Use os.fsencode() to Encode File System Paths of 3 Operating Systems

The fsencode() method is a part of the os module available in Python. The fsencode() method encodes the passed filename to file system encoding.

The encoded filename can be decoded back with the help of the fsdecode() method.

Syntax of Python os.fsencode() Method

os.fsencode(filename)

Parameters

Type Description
filename string/byte string A string or bytes object representing a valid file system path.

Returns

The fsencode() method returns an encoded filename in the form of a byte string.

Example Code: Use os.fsencode() to Encode File System Paths of 3 Operating Systems

import os

f1 = "/home/user/Photos/School-Trip.zip" # Linux path (string)
f2 = "D:\\User\\Photos\\School-Trip.zip" # Windows path (string)
f3 = "/Users/Username/Desktop/Photos/School-Trip.zip" # MacOS path (string)
f4 = b"/home/user/Photos/School-Trip.zip" # Linux path (bytes string)
f5 = b"D:\User\Photos\School-Trip.zip" # Windows path (bytes string)
f6 = b"/Users/Username/Desktop/Photos/School-Trip.zip" # MacOS path (bytes string)
print(os.fsencode(f1))
print(os.fsencode(f2))
print(os.fsencode(f3))
print(os.fsencode(f4))
print(os.fsencode(f5))
print(os.fsencode(f6))

Output:

b'/home/user/Photos/School-Trip.zip'
b'D:\\User\\Photos\\School-Trip.zip'
b'/Users/Username/Desktop/Photos/School-Trip.zip'
b'/home/user/Photos/School-Trip.zip'
b'D:\\User\\Photos\\School-Trip.zip'
b'/Users/Username/Desktop/Photos/School-Trip.zip'

With the help of the fsencode() method, the Python code above encodes 6 file system paths. Out of the 6 paths, 3 paths are strings, and the remaining are byte strings.

Moreover, file systems paths of Linux, Windows, and macOS operating systems are selected.

Vaibhav Vaibhav avatar Vaibhav Vaibhav avatar

Vaibhav is an artificial intelligence and cloud computing stan. He likes to build end-to-end full-stack web and mobile applications. Besides computer science and technology, he loves playing cricket and badminton, going on bike rides, and doodling.

LinkedIn GitHub

Related Article - Python OS

  • Python os.set_handle_inheritable() Method
  • Python os.set_inheritable() Method
  • Python os.stat_result Class
  • Python os.renames() Method
  • Python os.get_handle_inheritable Method
  • Python os.get_inheritable Method