Search code examples
pythonpathlib

How to get relative paths with Pathlib


I started using from pathlib import Path in place of os.path.join() to concatenate my paths. Taking the following code into consideration:

from pathlib import Path
import cv2

rootfolder = "rootyrooty"
file = "alittlefile"
image_path = Path(rootfolder, file)
image = cv2.imread(image_path.as_posix())

I'm using image_path.as_posix() to get a full string so I can pass image_path into imread function. Directly typing image_path doesn't works since it returns WindowsPath('rootyrooty/alittlefile') but I need "rootyrooty/alittlefile" (Since imread accepts strings instead of windowsPath objects). Do I have to use another component from pathlib instead of Path so I can just feed image_path into imread function. Like:

from pathlib import thefunctionyetidontknow
image_path = thefunctionyetidontknow("rootyrooty","alittlefile")
print("image_path")
# returns "rootyrooty/alittlefile"

Thanks.


Solution

  • The way you are combining paths is perfectly fine. What is questionable is the usage of as_posix() on a Windows machine. Some libs that accept a string as a path may be fine with posix path separators, but it may be preferable to use the os separator instead. To get path with filesystem separators, use str.

    See https://docs.python.org/3/library/pathlib.html

    The string representation of a path is the raw filesystem path itself (in native form, e.g. with backslashes under Windows), which you can pass to any function taking a file path as a string:

    >> p = PurePath('/etc')
    >> str(p)
    '/etc'
    >> p = PureWindowsPath('c:/Program Files')
    >> str(p)
    'c:\\Program Files'