xavier
xavier

Reputation: 816

How can I convert a pathlib.Path object to a string?

I read that pathlib is the new Python way to deal with paths.

So I do:

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

When I print image_path I get the full path to the image, but when I try to pass it to a function that uses ffmpeg to create a video file, I get:

TypeError: Can't convert 'PosixPath' object to str implicitly

I suspect this is because the object is Posix and the ffmpeg shell command expects a string.

In other cases I also got related error messages like

TypeError: 'PosixPath' object does not support indexing

or

TypeError: object of type 'PosixPath' has no len()

So how do you transform a Posix path to a string?

Upvotes: 15

Views: 28808

Answers (2)

Fusion
Fusion

Reputation: 5482

image_path.as_posix()
# Output: "/some/path/picture.png"

image_path.as_uri()
# Output: "file://some/path/picture.png"

Upvotes: 4

glibdud
glibdud

Reputation: 7880

Python can't do it implicitly, but you can do it explicitly:

str(image_path)

Upvotes: 24

Related Questions