0

I want to create a python package with below folder structure:

/package
  /package
    __init__.py
    /main
      __init__.py
      main.py
      ...
    /data
      __init__.py
      constants.py  <--
      data.yml
  pyproject.toml
  ...

And inside constants.py, I defined the path to data.yml: DATA_PATH = './data.yml' and used it in main.py:

from package.data.constants import DATA_PATH

with open(DATA_PATH, 'r') as f:
    ...

Then I build and installed the package into another project.

But when some code of main is used, it complains about "No such file or directory".

I also tried './data/data.yml' and './package/data/data.yml'and none worked.

How should I define the path?

CSSer
  • 2,131
  • 2
  • 18
  • 37
  • The problem is that main.py could be run from any working directory. You could use [`os.path` and `__file__`](https://stackoverflow.com/questions/50499/how-do-i-get-the-path-and-name-of-the-file-that-is-currently-executing) to find the location of `constants.py` when that is running, and add `data.yaml` to that path – Stuart Feb 28 '23 at 14:49

1 Answers1

0

You assign the string literal './data.yml' to the variable DATA_PATH. In main.py Python addresses that as a relative path, searching for a file named data.yml within the directory main.py is in (.../package/main/).

You can assign the absolute path of data.yml instead. So in constants.py:

import os

...

DATA_PATH = os.path.join(os.path.dirname(__file__)), 'data.yml')
NLavie
  • 61
  • 3