Python: import file from another directory

I am working in a set of directories with the following structure:

Master/
      Subfolder_1/file_1_1.py
                  file_1_2.txt
      Subfolder_2/file_2_1.py

      

I am importing file_1_1 to file_2_1 like this:

import sys
sys.path.append('../file_1_1')

      

file_1_1 reads file_1_2.txt, which is in the same directory. However, when I call a function that reads file_1_2.txt from file_2_1.py, there is no such file and directory in it, and it gives me the path to file_1_2.txt like:

Master/Subfolder_2/file_1_2.txt

      

which is the wrong way. It looks like python is using the working directory as a reference in this case. How can I resolve this error, given that I don't want to include an absolute path for every file read.

+3


source to share


1 answer


Don't mess with sys.path

and think of import as working with files and directories. Ultimately everything has to live somewhere in the file, but the module hierarchy is a little more subtle than "replace full with a slash and insert" .py at the end ".

You almost certainly want to be in Master

and run python -m Subfolder_1.file_1_1

. You can use pkg_resources to get a text file:



pkg_resources.resource_string('Subfolder_1', 'file_1_1.txt')

      

+1


source







All Articles