首页 > 解决方案 > 如何使用 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'

标签: pythonpython-3.x

解决方案


首先,~/path/to/file始终是绝对路径(~扩展为$HOME)。要在 Python 中进行此替换,您需要使用os.path.expanduser以下命令:

with open(os.path.expanduser("~/scripts/config.yml"), 'r') as ymlfile:
    cfg = yaml.load(ymlfile)

推荐阅读