Python将str转换为路径类型?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26124281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python convert a str to path type?
提问by realityinabox
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.
我正在尝试与一些保存配置的现有代码进行交互,并且需要一个类型为“path.path”的文件路径。该代码期望从 pygtk 浏览器窗口(通过另一个函数)返回文件路径。我想使用基于不同输入的文件路径在我的代码中的其他地方调用 save_config 函数,该文件路径由字符串元素构成。
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.
当我尝试运行代码时,我能够正确构造文件路径,但它是一个字符串类型,并且保存函数需要一个 'path.path' 类型。
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.
有没有办法将字符串转换为路径类型?我试过搜索,但只能找到相反的情况(字符串路径)。我也尝试使用os.path.join(),但这也会返回一个字符串。
edit: This is python 2.7, if that makes a difference.
编辑:这是 python 2.7,如果这有区别的话。
回答by Bryan Oakley
If path.pathrepresents a type, you can probably create an instance of that type with something like:
如果path.path代表一种类型,您可能可以使用以下内容创建该类型的实例:
string_path = "/path/to/some/file"
the_path = path.path(string_path)
save_config(the_path()
回答by Daniel
Maybe that answer worked for python 2.7, if you are on Python 3 I like:
也许这个答案适用于 python 2.7,如果你使用的是 Python 3,我喜欢:
import os
p = "my/path/to/file.py"
os.path.normpath(p)
'my\path\to\file.py'
回答by Ray
Since python 3.4:
从 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
https://docs.python.org/3/library/pathlib.html#module-pathlib

