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 typepath = str("./usr/")# instance of bytes typebytesObject = bytes(10)# calling fspath()# extracting the file system representationprint("String path:", os.fspath(path))print("Bytes path:", os.fspath(bytesObject))
Explanation
- Line 3: The
pathcontains a string of directory. - Line 5:
bytesObjectcontains a sequence of10bytes. - Line 8: We invoke the
os.fspath()method to extract the file systempath="./usr/"demonstration. - Line 9: We invoke
os.fspath()method to extract the file systempath= bytesdemonstration.
import randomimport os# integer valuevalue = random.randint(1,10)# It will throws exceptionprint(os.fspath(value))
- Line 4: A variable value containing a random value between
1-10. - Line 6: We invoke
os.fspath()withinttype value. Moreover, it throws aTypeErrorexception because it takes onlystrorbytes.
Note:
TypeError: expectedstr,bytesoros.PathLikeobject, notint