我开始使用?grep
代替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"
接受字符串而不是windowsPath对象)。我是否必须使用imread
中的另一个组件而不是pathlib
,以便可以将Path
馈入image_path
函数中。喜欢:
imread
谢谢。
答案 0 :(得分:1)
您可以使用Python的内置Path
函数将str
对象转换为字符串:
from pathlib import Path
import cv2
rootfolder = "rootyrooty"
file = "alittlefile"
image_path = Path(rootfolder, file)
image = cv2.imread(str(image_path))
答案 1 :(得分:1)
组合路径的方式非常好。
令人怀疑的是Windows计算机上as_posix()
的用法。某些接受字符串作为路径的库可以使用posix路径分隔符,但最好使用os分隔符。要使用文件系统分隔符获取路径,请使用str
。
请参见https://docs.python.org/3/library/pathlib.html
路径的字符串表示形式是原始文件系统路径本身(本机格式,例如Windows下的反斜杠),您可以将其传递给将文件路径作为字符串的任何函数:
>> p = PurePath('/etc') >> str(p) '/etc' >> p = PureWindowsPath('c:/Program Files') >> str(p) 'c:\\Program Files'