Python将str转换为路径类型? [英] Python convert a str to path type?

查看:2846
本文介绍了Python将str转换为路径类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试与一些保存配置的现有代码交互,并期望文件路径为'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.

当我尝试运行代码时,我能够正确地构造文件路径,但是它是字符串类型,并且save函数期望使用'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.

edit: 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

这篇关于Python将str转换为路径类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆