0

I have a structure such has:

/mainfolder
file.py
    //subfolder
    test.py

I am trying to import file.py in test.py. for some reason I just can't.

I tried

from .file import *

returning :

Traceback (most recent call last):
ModuleNotFoundError: No module named '__main__.file'; '__main__' is not a package

also tried to add path to sys.path:

import sys
import os
sys.path.extend([os.getcwd()])

doesnt work either

Steven G
  • 16,244
  • 8
  • 53
  • 77

2 Answers2

1

What IDE are you using? I am using Pycharm Community IDE with Python 3 and it works with from file import * or from file import some_function (I wanted to comment but I can't since I don't have 50 reputation yet)

return
  • 291
  • 1
  • 13
1

Looks like you're running test.py with python test.py and as such the test module is being treated as a top level module.

You should first make your folders Python packages if they are not by adding __init__.py files:

/mainfolder
__init__.py
file.py
    /subfolder
    __init__.py
    test.py

Then you can append the outer mainfolder to sys.path:

import sys
import os
sys.path.append(os.path.join(os.getcwd(), '..'))

After which from file import someobject without relative import works. Be wary of wild card imports.

See ModuleNotFoundError: What does it mean __main__ is not a package? and How to do relative imports in Python? for more on why your current approach does not work.

Community
  • 1
  • 1
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
  • assuming that I have a test2.py in //subfolder and test.py has from file import * at the start, how can I import test.py in test2.py? – Steven G May 02 '17 at 15:28
  • Discard `import *`. Specify explicitly what you want to have imported. If `subfolder` is a subpackage, then `import .test` or `from mainfolder.subfolder import test` should be fine – Moses Koledoye May 02 '17 at 15:31