import files from same directory in VSCode

Question:

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 !

Asked By: Antoine Krajnc

||

Answers:

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.

Answered By: saintlyzero