Python os.fspath() Method

Vaibhav Vaibhav Aug 31, 2022
  1. Syntax
  2. Parameters
  3. Returns
  4. Exception
  5. Examples
Python os.fspath() Method

The fspath() method belongs to the os module of Python programming. The os module offers utilities to work with the operating system.

The fspath() method returns the file system representation of the path. Remember, the __fspath__() is called which returns either bytes, os.PathLike, or str.

Syntax

os.fspath(path)

Parameters

Type Explanation
path string/bytes A file system path.

Returns

The fspath() method returns the file system representation of a path. The output’s type depends on the type of input.

  • If the input is a string, the output is a string.
  • If the input is a bytes string, the output is a bytes string.
  • If the input is os.PathLike, the output is an os.PathLike.

Exception

We will get the TypeError exception if the path is neither bytes type nor str type.

Examples

String Path

Example Code:

from os import fspath

#here, the `path` is a string type
path = "/home/users/documents/data.json"
print(fspath(path))

Output:

/home/users/documents/data.json

Bytes String Path

Example Code:

from os import fspath

#here, the `path` is bytes string type
path = b"/home/users/documents/data.json"
print(fspath(path))

Output:

b'/home/users/documents/data.json'

Example Code:

import os

# create bytes' type instance
bytesObject = bytes(10)
print(os.fspath(bytesObject))

Output:

b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

Neither String Nor Bytes Path

Example Code:

import random
import os

#generate a random value between 1-5
#and assign to `path` variable
path = random.randint(1,5)

# It will raise an exception
print(os.fspath(path))

Output:

Traceback (most recent call last):
  File "/home/jdoodle.py", line 6, in <module>
    print(os.fspath(path))
TypeError: expected str, bytes or os.PathLike object, not int

According to the documentation, if we pass bytes or str, it would be returned unchanged. Otherwise, the __fspath__() function would be called and will return its value as long as it’s bytes or str object.

In all other cases, except this, the TypeError exception is raised. So, remember that if we have the correct path type but are not written correctly, for instance, if we miss double quotes, then we will get SyntaxError: invalid syntax.

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