Load file from same folder as Python 3.x script inside package

177 Views Asked by At

Opening and loading data from a file that is situated in the same folder as the currently executing Python 3.x script can be done like this:

import os

mydata_path = os.path.join(os.path.dirname(__file__), "mydata.txt")
with open(mydata_path, 'r') as file:
    data = file.read()

However once the script and mydata.txt files become part of a Python package this is not as straight forward anymore. I have managed to do this using a concoction of functions from the pkg_resources module such as resource_exists(), resource_listdir(), resource_isdir() and resource_string(). I won't put my code here because it is horrible and broken (but it sort of works).

Anyhow my question is; is there no way to manage the loading of a file in the same folder as the currently executing Python script that works regardles of wether the files are in a package or not?

1

There are 1 best solutions below

1
a_guest On

You can use importlib.resources.read_text in order to read a file that's located relative to a package:

from importlib.resources import read_text

data = read_text('mypkg.foo', 'mydata.txt')