pathlib to str

String to path object with Pathlib

from pathlib import Path

path_str = '/var/www/somesite'
path_obj = Path(path_str)

Pathlib path to string

from pathlib import PurePath

my_lib_dir = PurePath(__file__).parent.parent / 'lib'

sys.path.insert(0, str(my_lib_dir) )  # add my libraries dir
# or
sys.path.insert(0, f'{my_lib_dir}')

Example: str to pathlib, pathlib to str

#!/usr/bin/python3

from pathlib import Path

path_str = '/var/www/somesite'

print(repr(path_str))            # '/var/www/somesite'
print('type:', type(path_str))   # type: <class 'str'>
print()

path_obj = Path(path_str)
print(repr(path_obj))            # PosixPath('/var/www/somesite')
print('type:', type(path_obj))   # type: <class 'pathlib.PosixPath'>
print()

path_str2 = str(path_obj)
print(repr(path_str2))           # '/var/www/somesite'
print('type:', type(path_str2))  # type: <class 'str'>
print()

Last updated