If I have a file structure like this:
mydir/
├── myfile.txt
└── myscript.py
I can access myfile.txt
within myscript.py
like so:
import os
dir = os.path.dirname(__file__)
with open(dir + "myfile.txt") as f:
...
# Do something
How do I replicate this behavior if I add an __init__.py
file and build mydir
as a distributable package? Does it depend on how you build the distribution?
I’m very new to writing packages and so far I’ve only ever used setuptools to create a package that I could pip install on my local machine. I’ve done this before with yaml files, using include_package_date=True
in my setup.py
file. I used something like this within the package to access yaml files:
import pkgutil
import yaml
def _open_internal_yaml(internal_yaml_path) -> str:
yaml_bytes: bytes | None = pkgutil.get_data(
__name__, internal_yaml_path
)
if yaml_bytes is None:
raise Exception(
"Something went wrong with call to `pkgutil.get_data`.n"
f"Got 'None' when loading '{internal_yaml_path}'."
)
yml = yaml.safe_load(yaml_bytes.decode())
return yml
where internal_yaml_path
is relative to the directory of the file that holds the above code.
Is there a more efficient or pythonic way to do this?
Andrew Benfante is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.