简体   繁体   中英

Importing module from "outer" directory [Python]

I have seen a lot of answers over this simple problem but I can't find a good solution for such, even a workable solution; the problem is, I have this proyect structure

parent_folder
   |
   |__folder1
   |    |_____ __init__.py
   |    |_____ file1.py 
   |
   |__folder2
        |_____ __init__.py  
        |_____file2.py  

I want to call a function (lets name it function2) from file2.py inside file1.py, but when doing an import like this:

# inside file1.py

from folder2.file import function2

I get the following error:

ModuleNotFoundError: No module named 'folder2'

Then I tried using absolute import, so the code looked like:

# inside file1.py

from ..folder2.file2 import function2

And I get the following error:

ImportError: attempted relative import with no known parent package

And finally I tried adding such directory to my path using the following code:

#inside file1.py

import sys
sys.path.append("..")

from ..folder2.file2 import function2

And still, get the same error:

ImportError: attempted relative import with no known parent package

What is the definitive CLEAN solution for such problem?,I would appreciate an answer, thanks

NOTE: My current Python version is 3.8 and the code is running under Windows 10

file1.py

import os
import sys
sys.path.append(os.path.dirname(os.getcwd()))
from folder2.file2 import function2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM