Convert a str to path type?

106,811

Solution 1

Since python 3.4:

from pathlib import Path
str_path = "my_path"
path = Path(str_path)

https://docs.python.org/3/library/pathlib.html#module-pathlib

Solution 2

Maybe that answer worked for python 2.7, if you are on Python 3 I like:

import os

p = "my/path/to/file.py"
os.path.normpath(p)
'my\\path\\to\\file.py'

Solution 3

If path.path represents a type, you can probably create an instance of that type with something like:

string_path = "/path/to/some/file"
the_path = path.path(string_path)
save_config(the_path()
Share:
106,811
realityinabox
Author by

realityinabox

Updated on July 17, 2022

Comments

  • realityinabox
    realityinabox almost 2 years

    I am trying to interface with some existing code that saves a configuration, and expects a file path that is of type path.path. The code is expecting that the file path is returned from a pygtk browser window (via another function). I want to call the save_config function elsewhere in my code with a file path based on different inputs, constructed from string elements.

    When I try to run the code, I am able to construct the file path correctly, but it is a string type, and the save function expects a path.path type.

    Is there a way to convert a string to a path type? I've tried searching, but could only find the reverse case (path to string). I also tried using os.path.join(), but that returns a string as well.

    Edit: This is python 2.7, if that makes a difference.