Python os.fspath() Method

Python os.fspath() method is used to get the file system representation of a path-like object.

A path-like object is either a string or bytes object representing a path or an object implementing the __fspath__() method, which returns either a string or bytes object.

The main purpose of this method is to simplify the handling of different path representations, allowing functions and methods that handle file system paths to work with various types of path representations in a consistent manner.

Syntax

os.fspath(path)

Parameters

path: It is a path-like object.

Return value

It is a str or bytes value representing the file system path.

Example 1: Using os.fspath() with a String Path

import os

path_str = "/Users/krunallathiya/Desktop/Code/pythonenv/env/data.txt"

# Convert to file system path
fs_path = os.fspath(path_str)

print(fs_path)

Output

/Users/krunallathiya/Desktop/Code/pythonenv/env/data.txt

Example 2: Using bytes path

import os

path_bytes = b"/Users/krunallathiya/Desktop/Code/pythonenv/env/data.txt"

# Convert to file system path
fs_path = os.fspath(path_bytes)

print(fs_path)

Output

b'/Users/krunallathiya/Desktop/Code/pythonenv/env/data.txt'

Example 3: Using a custom path-like Object

import os


class CustomPath:
  def __init__(self, path):
    self._path = path

  def __fspath__(self):
    return self._path


# Create an instance of CustomPath
custom_path = CustomPath(
  "/Users/krunallathiya/Desktop/Code/pythonenv/env/data.txt")

# Convert to file system path
fs_path = os.fspath(custom_path)

print(fs_path)

Output

/Users/krunallathiya/Desktop/Code/pythonenv/env/data.txt

Example 4: TypeError: expected str, bytes or os.PathLike object, not NonPathObject

TypeError will occur if the argument passed to the function is not a path-like object (i.e., it is neither a string, a bytes object, nor an object implementing the __fspath__() method).

import os


# Define a non-path-like object
class NonPathObject:
  def __init__(self, value):
    self.value = value


# Create an instance of the non-path-like object
non_path_instance = NonPathObject(42)

try:
  # Attempt to use os.fspath() on a non-path-like object
  fs_path = os.fspath(non_path_instance)
except TypeError as e:
  print("TypeError:", e)

Output

TypeError: expected str, bytes or os.PathLike object, not NonPathObject

That’s it!

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.