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?

1 Answer 1

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')
Sign up to request clarification or add additional context in comments.

1 Comment

At least that is something. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.