如何使用Pathlib获取相对路径

2024-10-01 15:49:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我开始使用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不起作用,因为它返回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"

谢谢


Tags: path字符串fromimageimportascv2posix
2条回答

您组合路径的方式非常好。 值得怀疑的是as_posix()在Windows计算机上的使用。一些接受字符串作为路径的lib可以使用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'

可以使用Python的内置函数strPath对象转换为字符串:

from pathlib import Path
import cv2

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

相关问题 更多 >

    热门问题