theX
theX

Reputation: 1134

Is it possible to import a python file from outside the directory the main file is in?

I have a file structure that looks like this:

Liquid
|
[Truncate]
|_General_parsing
[Truncate]
.....|_'__init__.py'
.....|_'Processer.py'
.....|'TOKENIZER.py'
|_'__init__.py'
|_'errors.py'
[Truncate]

I want to import errors.py from Processer.py. Is that possible? I tried to use this:

from ..errors import *; error_manager = errorMaster()

Which causes this:

Traceback (most recent call last):
  File "/Users/MYNAME/projects/Liquid/General_parsing/Processer.py", line 17, in <module>
    from ..errors import *; error_manager = errorMaster()
ImportError: attempted relative import with no known parent package
[Finished in 0.125s]

I've seen this post, but it's no help, even if it tries to solve the same ImportError. This isn't, either (at least not until I edited it), since I tried:

import sys
sys.path.insert(1, '../Liquid')
from errors import *; error_manager = errorMaster()

That gives


Traceback (most recent call last):
  File "/Users/MYNAME/projects/Liquid/General_parsing/Processer.py", line 19, in <module>
    from errors import *; error_manager = errorMaster()
ModuleNotFoundError: No module named 'errors'
[Finished in 0.162s]

EDIT: Nevermind! I solved it! I just need to add .. to sys.path! Or . if .. doesn't solve your problem. But if those don't solve your problem: use some pathlib (came in python3.4+) magic and do:

from pathlib import Path
import sys
sys.path.insert(0, str(Path(__file__).parent))

or, if you want to use os: (gotten from this StackOverflow answer)

import os
os.path.join(os.path.dirname(__file__), '..')

Upvotes: 3

Views: 1323

Answers (1)

theX
theX

Reputation: 1134

I solved it! I have to add .. to sys.path instead

Upvotes: 2

Related Questions