I am trying to import a module from another directory that stems from the same parent. I got the code to work in Python 2.7 but not in Python 3.5.
I'm working in py_file.py ===> H:/other/apple/work_here/py_file.py
I want to import total_text.py from ===> H:/other/apple/banana/total_text.py
The import works in Python 2.7 but not in Python 3.5. In 3.5 I get a red squiggly line under banana and when I run the code the error reads "No module named 'banana'"
import sys
import os
os.chdir(os.path.join("H:\\", "other", "apple", "work_here"))
sys.path.insert(0, os.path.join(os.path.split(__file__)[0], ".."))
import banana.total_text
To troubleshoot the problem, I executed the following print statements in both programs and found I am getting mixed slashes in Python 3.5 program.
In Python 2.7, I get:
print sys.path[0] =====> H:\other\apple\work_here.. # Note there is a \ after the e in here that did not show up.
print os.listdir(sys.path[0]) =====> [u'banana', u'work_here']
In Python 3.5 I get the following:
print sys.path[0] =====> H:/other/work_here.. # Note there is a \ after the e in here that did not show up.
print os.listdir(sys.path[0]) =====> ['apple', 'work_here']
I searched around and found a partial fix: By adding os.path.abspath(x) or os.path.normpath(x) where x = os.path.join(os.path.split(file)[0], "..") I got it to go back two directories to H:\other ===> The import statement works if I write it like: import apple.banana.total_text
Using the os.path.abspath() version, I get:
print(sys.path[0]) =====> H:\other
print(os.listdir(sys.path[0])) =====> ['apple', 'work_here']
I am trying to get the Python 3.5 version to work the same way as the Python 2.7 version and understand if what would cause 3.5 to behave differently.