0

Please don't delete this. this is so simple but I'm banging my head making this work for last two hours.

As displayed. I want to import python file module_dir into module_sub_dir.py, but its giving erros. all init.py are empty.enter image description here

from .. import module_dir

This doesn't work either as it gives erro

ImportError: attempted relative import with no known parent package
6
  • 1
    How are you running the script? Are you running python sub_dir/module_sub_dir.py? Commented Apr 19, 2022 at 18:05
  • 1
    Starting python 2.5 you can import from parent using three dots: from ... import module_dir Commented Apr 19, 2022 at 18:05
  • @mikicz I have opened 'dir' folder (main/root folder) in VS code. Commented Apr 19, 2022 at 18:07
  • @PietroD'Antuono got error ImportError: attempted relative import with no known parent package Commented Apr 19, 2022 at 18:08
  • 1
    If you have dir folder open, then you shall import directly from the current folder. Then it is: from . import module_dir. Also, the folder containing module_dir.py must contain an __init__.py as well to be "recognized" as a python package Commented Apr 19, 2022 at 18:10

2 Answers 2

1

Add sys.path.append("..") to the very beginning then importlib will be able to reach the file in parent directories of CWD. But I recommend you not to use such ugly solution in your projects.

Sign up to request clarification or add additional context in comments.

2 Comments

Yeah, I'm trying to avoid that, I see that people making it work without sys.path but for some reason this is not working for me.
Another way to do something similar would be to define the environment variable PYTHONPATH to point to dir
0

Update as I have figured out the issue myslef.

So the issue is how VS Code runs .py file individually as oppose to running entire package like Pycharm. It works in Pycharm. To make it work in VS Code sys.import.path('..') works.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.