0

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?

Mr. Developerdude
  • 9,118
  • 10
  • 57
  • 95

1 Answers1

2

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')
a_guest
  • 34,165
  • 12
  • 64
  • 118