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.
3 Answers 3
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
Comments
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'
Comments
path.path isn't a standard python type. Without knowing what path.path actually is in your environment, if path.path represents a class then you can probably create an instance of that with something like this:
string_path = "/path/to/some/file"
the_path = path.path(string_path)
save_config(the_path)
path.path(config_string)path.path? Sounds like a class that is defined by the code you are using; it's not a standard type or class. Prior to Python 3.4, there was no standard for paths; functions operating on paths just used the string representation. Python 3.4 introduced thepathlibmodule, which provides proper objects to represent paths.type(file_path), I get<class 'path.path'>as a response. There is afrom path import pathline at the top of my file. I'm assuming this is justos.path, but I'm new to this, and the guy who wrote this tool left the company.os.pathwhich is a module in the standard library, so it must be something else. After theimport, see whathelp(path)says — there may be something that does what you want.