0

I can't for the life of me figure out what's wrong here. I'm trying to import a local library that's in an upstream path:

root/
    folder1/
        test1.py
    folder2/
        test2.py

In this scenario I want to import folder1 in test2.py.

In test2.py, I use sys.path.append to add the file path to folder1:

import os
import sys
fileDir = os.path.dirname(os.path.abspath(__file__))
parentDir = os.path.dirname(fileDir)
sys.path.append(os.path.join(parentDir, 'folder1'))

print(sys.path)
import folder1.test1

But when I'm in root and run python3 folder2/test2.py, I still get ModuleNotFoundError: No module named 'folder1'.

I've also tried hardcoding $PYTHONPATH and it still doesn't work.

doctopus
  • 5,349
  • 8
  • 53
  • 105
  • Path stores where to look for modules. Right now your code seeks `folder1` module **in** folder1 directory! Just do `import test1`, because that's what **in** folder1. Or add parentDir (without specifying) folder1 to path. – h4z3 Apr 23 '20 at 14:05
  • Similar question as this: https://stackoverflow.com/questions/61322726/how-to-import-modules-from-a-file-in-a-deeper-directory/61326547#61326547 You should remove the `join`. Then you can do `import folder1.testx`. With the the `join` it would just be `import testx` – Tin Nguyen Apr 23 '20 at 14:06
  • Got it, thanks for the help!! – doctopus Apr 24 '20 at 02:14

0 Answers0