user3558855 user3558855 - 3 months ago 18
Python Question

Access files relative to imported python module

Preliminary:

I have Anaconda 3 on Windows 10, and a folder,

folder_default
, that I have put on the Python path. I'm not actually sure whether that's the right terminology, so to be clear: regardless to where my Python script is, if I have a line of code that says
import myFile
, that line of code will succeed if
myFile.py
is in
folder_default
.

My issue:

In
folder_default
, I have:


  1. A subfolder called
    useful_files
    which contains a text file called
    useful_file_1.txt
    .

  2. A python script called
    my_misc.py
    .



my_misc.py
has a line similar to:
np.loadtxt('useful_files/useful_file_1.txt')
. This line does not work if I use
import my_script
in a python file in a location other than
folder_default
, since
useful_files/useful_file_1.txt
is not the folder path relative to the python file that imports
my_misc.py
. I don't want to start using global file paths if I can avoid it.

How can I access files using file paths relative to the imported python module, rather than relative to the python script that imports that module?

Please let me know if the question is unclear - I tried to write a fake, minimal version of the setup that's actually on my computer in the hopes that that would simplify things, but I can change it if that actually makes things more confusing.

Thanks.

Answer

You can get the path to current module using the getfile method of inspect module as inspect.getfile(inspect.currentframe()). For example:

# File : my_misc.py
import os, inspect

module_dir_path = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) # get path to the directory of current module
useful_file_path = os.path.join(module_dir_path,'useful_files','useful_file_1.txt')
# path stored in useful_file_path. do whatever you want!

np.loadtxt(useful_file_path)