python - 如何使用 open() 在 python 中打开具有相对路径的文件?
问题描述
我试图不为我的配置文件使用绝对路径,因为我需要将它部署在多个环境中,我最好的选择是什么
下面的代码是我尝试过的,它无法找到路径,但是我可以将文件放在同一位置。我在 Redhat 服务器上使用 Python3.6。
with open("~/scripts/config.yml", 'r') as ymlfile:
cfg = yaml.load(ymlfile)
我收到以下错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: '~/scripts/config.yml'
解决方案
首先,~/path/to/file
始终是绝对路径(~
扩展为$HOME
)。要在 Python 中进行此替换,您需要使用os.path.expanduser
以下命令:
with open(os.path.expanduser("~/scripts/config.yml"), 'r') as ymlfile:
cfg = yaml.load(ymlfile)
推荐阅读
- android - 未知来源的空指针异常 (Ud.f)
- reactjs - 反应 | Ant Design - 使用远程数据搜索的 Select 组件中的默认值
- python - 生成带有条件的列表产品
- docusignapi - Docusign - HTTP/1.1://docusignapp2.herokuapp.com?op=webhook :: 错误 - 无效的 URI:URI 方案无效
- go - Golang GCP 存储客户端内存泄漏
- shell - 在 Unix 中杀死存储在文本文件中的进程 ID
- php - 根据另一个选择更改选择选项
- c# - 如何使用 C# 在 WindowsForm 中播放 HLS-(Http Live Streaming)?
- asp.net - ASP.net Core 3.1 Razor 页面分页控件不适用于 dapper 数据集
- python - 如果任何行值在另一个数据框中,则从数据框中删除一行,数据框有多个列