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 anos.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
.
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