What is os.fspath() function in Python?

Overview

This os.fspath() method is used to extract the file system representation of the specified path. The __fspath__() function is called that returns either str, bytes or os.PathLike object.

Note: Abstract method __fspath__() is called which return exact file system path representation.

Syntax


os.fspath(path)

Parameters

It takes a single value as an argument:

  • path: It can be an instance of string or bytes type.

Return value

It will either return str, bytes or os.PathLike like object.

Exception

TypeError: When the path is neither str nor bytes , the type error exception will be raised.

Explanation

Now, let’s elaborate on this method with a detailed example:

import os
# instance of string type
path = str("./usr/")
# instance of bytes type
bytesObject = bytes(10)
# calling fspath()
# extracting the file system representation
print("String path:", os.fspath(path))
print("Bytes path:", os.fspath(bytesObject))

Explanation

  • Line 3: The path contains a string of directory.
  • Line 5: bytesObject contains a sequence of 10 bytes.
  • Line 8: We invoke the os.fspath() method to extract the file system path="./usr/" demonstration.
  • Line 9: We invoke os.fspath() method to extract the file system path= bytes demonstration.
import random
import os
# integer value
value = random.randint(1,10)
# It will throws exception
print(os.fspath(value))
  • Line 4: A variable value containing a random value between 1-10.
  • Line 6: We invoke os.fspath() with int type value. Moreover, it throws a TypeError exception because it takes only str or bytes.

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

Free Resources