Python: import a file from another directory -
i working in set of directories following structure:
master/ subfolder_1/file_1_1.py file_1_2.txt subfolder_2/file_2_1.py
i import file_1_1 in file_2_1 follows:
import sys sys.path.append('../file_1_1')
file_1_1 reading file_1_2.txt in same directory. however, when call function reads file_1_2.txt file_2_1.py, says no such file , directory , gives me path of file_1_2.txt as:
master/subfolder_2/file_1_2.txt
which wrong path. seems python in case using working directory reference. how can solve error given don't want include absolute path each file read.
don't mess sys.path
, , don't think of imports working against files , directories. has live in file somewhere, module hierarchy little more subtle "replace dot slash , stick .py @ end".
you want in master
, run python -m subfolder_1.file_1_1
. can use pkg_resources text file:
pkg_resources.resource_string('subfolder_1', 'file_1_1.txt')
Comments
Post a Comment