如何将 pathlib.Path 对象转换为字符串?

问题描述 投票:0回答:2

我读到

pathlib
是处理路径的新Python方法。

所以我这样做:

with open(pic_name, 'wb') as image:
    image.write(download.content)
    image_path = Path(pic_name).resolve()
    return image_path

当我打印

image_path
时,我获得了图像的完整路径,但是当我尝试将其传递给使用 ffmpeg 创建视频文件的函数时,我得到:

TypeError:无法将“PosixPath”对象隐式转换为 str

我怀疑这是因为对象是 Posix 并且 ffmpeg shell 命令需要一个字符串。

在其他情况下,我也收到相关的错误消息,例如

TypeError:“PosixPath”对象不支持索引

TypeError:“PosixPath”类型的对象没有 len()

那么如何将 Posix 路径转换为字符串呢?

python python-3.x pathlib
2个回答
19
投票

Python 无法隐式执行此操作,但您可以显式执行此操作:

str(image_path)

0
投票
image_path.as_posix()  # /some/path/picture.png
image_path.as_uri()  # file:////some/path/picture.png
© www.soinside.com 2019 - 2024. All rights reserved.