将 str 转换为路径类型? [英] Convert a str to path type?
问题描述
我正在尝试与一些保存配置的现有代码进行交互,并期望使用 path.path
类型的文件路径.该代码期望从 pygtk 浏览器窗口(通过另一个函数)返回文件路径.我想使用基于不同输入的文件路径在我的代码中的其他位置调用 save_config
函数,该文件路径由字符串元素构成.
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
类型.
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.
有没有办法将字符串转换为路径类型?我试过搜索,但只能找到相反的情况(字符串的路径).我也尝试使用 os.path.join()
,但它也返回一个字符串.
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.
这是 python 2.7,如果有区别的话.
This is python 2.7, if that makes a difference.
推荐答案
自 python 3.4 起:
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
这篇关于将 str 转换为路径类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!