user3558855 user3558855 - 1 year ago 97
Python Question

Access files relative to imported python module


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

, 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
is in

My issue:

, I have:

  1. A subfolder called
    which contains a text file called

  2. A python script called
has a line similar to:
. This line does not work if I use
import my_script
in a python file in a location other than
, since
is not the folder path relative to the python file that imports
. 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.


Answer Source

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

# File :
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!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download