1

I'm unable to import a .py file into another .py file. I thought things would be easy just by doing

import filename.py 

but I always get a ModuleNotFoundError

I've also tried :

from .filename import *
from filename import * 
from .filename import Class 
from . import filename 

I've also tried to add

import os, sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))

But that didn't work as well.

Would you guys see what I would be missing ?

Just to clarify :

  • I'm using Python3 on VSCode
  • Both my files are in the same directory.

Here is the structure

.
├── __pycache__
│   └── model.cpython-36.pyc
├── ai.py
├── model.py
└── recording
    ├── openaigym.video.0.2641.video000000.meta.json
    └── openaigym.video.0.2641.video000000.mp4

Thanks for your help !

Antoine Krajnc
  • 1,163
  • 10
  • 29
  • Sometimes (or always) modules are searched from the location of the main file. So you need to make the path relative to that and this could help https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time?rq=1 – J Arun Mani Sep 19 '19 at 17:28
  • Can you give a tree structure of your module and main file? – J Arun Mani Sep 19 '19 at 17:29
  • Could you provide the command being run in the terminal and show the folder structure? – Brett Cannon Sep 19 '19 at 19:07
  • To be clearer, I have two files, both in the same directory. I edited the question to provide the folder structure. I'm trying to import model.py into ai.py I'm using an Interactive Notebook on VSCode, so I'm running each part of my code as if it was a cell. I tried to simply do `python ai.py` but I get the same error – Antoine Krajnc Sep 20 '19 at 13:33
  • You shouldn't need the `.py` on the `import`. – Mark Ransom Sep 20 '19 at 14:15

1 Answers1

0

This might happen if your class name clashes with any of the existing python class

In your ai.py file do:


from model import Class_name 

If even this doesn't work, add an empty __init__.py file in the same directory where you have model.py and ai.py.

Note: Sometimes VSCode displays unresolved imports warning even though your code works perfectly fine.

Danny Varod
  • 17,324
  • 5
  • 69
  • 111
saintlyzero
  • 1,632
  • 2
  • 18
  • 26
  • 2
    Thanks a lot @saintlyzero. Indeed, it works ! I also found that actually simply restarting the kernel in VSCode makes it work. – Antoine Krajnc Sep 20 '19 at 15:56