Question

Below is my init.py which is located under pkg/settings

import yaml
import os

def Keypairs():
    print os.path.dirname(os.path.realpath(__file__))
    with open('keypairs.yaml') as f:
        return yaml.load(f)

I run the package: python -m pkg.test.first which has a relative import:

from ..settings    import Keypairs    
print Keypairs()

But I get

IOError: [Errno 2] No such file or directory: 'keypairs.yaml'

although the structure is:

pkg/
  __init__.py
  settings/
    __init__.py
    keypairs.yaml
  test/
    __init__.py
    first.py

What am I messing with the directories?

If I run the __init__.py (which is in settings) as a script it locates the file.

Was it helpful?

Solution 2

Edited

You are opening the file in the wrong directory, importing a module does not change your working directory. Do this instead

 import yaml 
 import os

 def Keypairs():
   print os.path.dirname(os.path.realpath(__file__))

   with open(os.path.join(os.path.dirpath(__file__),'keypairs.yaml')) as f:
     return yaml.load(f)

OTHER TIPS

Well it appears that since I run the file as a package, it takes as parent directory the one where the package is.

So you need to pass

basepath = os.path.dirname(__file__)
keypairs = os.path.abspath(os.path.join(basepath, "keypairs.yaml"))
with open(keypairs,'r') as f:
    return yaml.load(f)

or if you want an absolute:

with open("pkg/settings/keypairs.yaml",'r') as f:

And the most clean way with the help of @yorodm

with open(os.path.join(os.path.dirname(__file__),'keypairs.yaml')) as f:
    return yaml.load(f)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top