Steven G
Steven G

Reputation: 17122

how to import file.py from main folder if you are working in a subfolder python3

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

Upvotes: 0

Views: 371

Answers (2)

Moses Koledoye
Moses Koledoye

Reputation: 78556

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.

Upvotes: 1

return
return

Reputation: 301

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)

Upvotes: 1

Related Questions