2

I am trying to not use an absolute path for my configuration file because I need this deployed in multiple environments, what is my best option here

The Below code is what I have tried and it is not able to find the path, however I am able to cat the file in the same location. I am using Python3.6 on a Redhat server.

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

I am getting the below error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: '~/scripts/config.yml'
EngineJanwaar
  • 422
  • 1
  • 7
  • 14
  • 1
    What you are providing is not a relative path. ``~`` is a shell expansion (https://www.gnu.org/software/bash/manual/html_node/Tilde-Expansion.html), not unlike ``$HOME``. You have to do this expansion in Python explicitly. – MisterMiyagi Jul 02 '19 at 11:19
  • Possible duplicate of [How to get the home directory in Python?](https://stackoverflow.com/questions/4028904/how-to-get-the-home-directory-in-python) – MisterMiyagi Jul 02 '19 at 11:21

2 Answers2

7

First of all, ~/path/to/file is always an absolute path (~ expands to $HOME). To make this substitution in Python, you need to use os.path.expanduser such as:

with open(os.path.expanduser("~/scripts/config.yml"), 'r') as ymlfile:
    cfg = yaml.load(ymlfile)
ig0774
  • 39,669
  • 3
  • 55
  • 57
1

You can do it with:

import os
path = os.getenv('HOME') + '/scripts/config.yaml'

~ only works in shell, not in a Python string

jacalvo
  • 656
  • 5
  • 14