如何使用 Pathlib 获取相对路径

How to get relative paths with Pathlib

我开始使用 from pathlib import Path 代替 os.path.join() 来连接我的路径。考虑以下代码:

from pathlib import Path
import cv2

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

我正在使用 image_path.as_posix() 获取完整的字符串,这样我就可以将 image_path 传递给 imread 函数。直接输入 image_path 不起作用,因为它 returns WindowsPath('rootyrooty/alittlefile') 但我需要 "rootyrooty/alittlefile" (因为 imread 接受字符串而不是 windowsPath 对象)。我是否必须使用 pathlib 中的另一个组件而不是 Path,这样我就可以将 image_path 馈送到 imread 函数中。喜欢:

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

谢谢。

您可以使用 Python 的内置 str 函数将 Path 对象转换为字符串:

from pathlib import Path
import cv2

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

您组合路径的方式非常好。 有问题的是 as_posix() 在 Windows 机器上的用法。一些接受字符串作为路径的库可能可以使用 posix 路径分隔符,但最好使用 os 分隔符。要获取带有文件系统分隔符的路径,请使用 str.

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'