Python convert a str to path type?

偶尔善良 提交于 2020-01-22 18:03:33

问题


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.


回答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




回答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'



回答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()


来源:https://stackoverflow.com/questions/26124281/python-convert-a-str-to-path-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!