47

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.

martineau
  • 119,623
  • 25
  • 170
  • 301
realityinabox
  • 593
  • 1
  • 5
  • 14
  • `path.path(config_string)` – mdurant Sep 30 '14 at 15:17
  • 6
    What is `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 the `pathlib` module, which provides proper objects to represent paths. – chepner Sep 30 '14 at 15:22
  • When I run `type(file_path)`, I get `` as a response. There is a `from path import path` line at the top of my file. I'm assuming this is just `os.path`, but I'm new to this, and the guy who wrote this tool left the company. – realityinabox Sep 30 '14 at 15:47
  • It's not `os.path` which is a module in the standard library, so it must be something else. After the `import`, see what `help(path)` says — there may be something that does what you want. – martineau Jul 22 '21 at 18:07

3 Answers3

65

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

Ray
  • 787
  • 6
  • 9
26

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'
Daniel
  • 1,172
  • 14
  • 31
1

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())
smyril
  • 111
  • 10
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685