0

If I have the following directory structure:

Folder1/  
└─ Folder2/  
   ├─ a.py  
   └─ Subfolder2/  
      └─ b.py

Folder2/a.py contains some functions.

I want to import a function in b.py from another file(a.py) in the parent directory(Folder2).

Can you help me figure out how my child file can successfully import functions in a.py to b.py

I tried

from .Folder2 import a

I get the following error:

ImportError: attempted relative import with no known parent package
  • Does this answer your question? [ImportError: attempted relative import with no known parent package :(](https://stackoverflow.com/questions/63312692/importerror-attempted-relative-import-with-no-known-parent-package) – jthulhu Aug 25 '21 at 11:38
  • Have you had a look at any of the answers on [this](https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time) or other questions about relative imports? – Iguananaut Aug 25 '21 at 11:38
  • Yes, i did it but i didint find an answer –  Aug 25 '21 at 11:41

1 Answers1

0

You can use following statement:

import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import a 

The function sys.path.insert() will allow you to import python files from the defined path.

see doc for more information

Pompidou
  • 41
  • 2
  • I want to import functions inside the file a.py and i still get function is not defined –  Aug 25 '21 at 11:52
  • With functions do you mean other python files or modules? If you mean python files, where is the location of them? – Pompidou Aug 25 '21 at 13:51