Python import file from the same directory: ModuleNotFoundError: No module named

Viewed 2018

I have the following files. And I want to be able to run python web\file1.py in Mod1.

Mod1
  web
    __init__.py
    file1.py
    file2.py
  __init__.py

and in file1.py:

import web.file2

However, when I run the following command in the directory mod1:

....\Mod1> python .\web\file1.py
Traceback (most recent call last):
  File ".\web\file1.py", line 1, in <module>
    import web.file2
ModuleNotFoundError: No module named 'web'

I tried to change the content of file1.py to

from . import file2

and the error become

ImportError: attempted relative import with no known parent package
2 Answers

As I understood what You want, You want to have file2.py imported in file1.py

If that is correct, all You need to do is type this in file1.py

import file2

Happy Coding!

It seem you are trying to import web/file1. Since there is an init file at mod1, you should use this in Mod1

import .web.file1 as f1

Then this in file2

import .file1 as f1
Related