1

I created a Python package with a structure as follows:

pkg_dir
   -mypkg
       -folder1
           -_init_.py
           -do_calc_.py
       -folder2
           -_init_.py
           -my.json
.
.
.
setup.py

Inside the folder1/do_calc.py, I need to read the my.json file from folder2 and use it in folder1/do_calc.py.

I am importing this mypkg into another Python script, and I am calling the do_calc function. However, the script is failing because inside mypkg, this read statement in folder1/do_calc.py:

with open('../folder2/my.json') as f:
    jsn = json.load(f)

is failing; because it seems that ../ path refers to the Python script where mypkg is imported; and not mypkg relative path.

please advise with a simple example, how to set up a path inside the mypkg so that I can pass my.json to

sinoroc
  • 18,409
  • 2
  • 39
  • 70
jscriptor
  • 775
  • 1
  • 11
  • 26
  • Does this answer your question? [How to read a (static) file from inside a Python package?](https://stackoverflow.com/questions/6028000/how-to-read-a-static-file-from-inside-a-python-package) – sinoroc Mar 05 '22 at 09:30

1 Answers1

-1

I figured this one out and I hope by posting her, it may provide answer to folks who may run into same issue in the future. What I did is as follows:

filepath = resource_filename('mypkg', 'folder2/my.json')
with open(filepath, 'r') as my_jsn:
...

This allowed me to, inside the pkg, read a json file that I can use somewhere else inside the same pkg.

jscriptor
  • 775
  • 1
  • 11
  • 26
  • Use [_`pkgutil.get_data(...)`_](https://docs.python.org/3/library/pkgutil.html#pkgutil.get_data) or [_`importlib.resources`_](https://docs.python.org/3/library/importlib.html#module-importlib.resources). See also [this answer](https://stackoverflow.com/a/58941536). – sinoroc Mar 05 '22 at 09:29