Home > OS >  VSCode not able to import functions from other folder in same directory
VSCode not able to import functions from other folder in same directory

Time:05-16

Directory structure is as follows:

master -> src -> utils -> time.py  
master -> src -> features -> transformations.py

time.py has certain functions that transformations.py imports using the following :

from src.utils.time import robust_hour_of_iso_date

When I run the code using Run and Debug the following error occurs :

Exception has occurred: ModuleNotFoundError
No module named 'src'

How do I solve this error ? New to VSCode so please ask any details you may require.

CodePudding user response:

You can add the folder to the system path like this:

import sys
sys.path.insert(0, "INSERT_FULL_PATH_TO_UTILS_FOLDER")
from time import robust_hour_of_iso_date

But that would not work since there is already a module called time in python so you should rename it to something like "timeutils.py".

CodePudding user response:

In the python language, the import usually only looks in the current directory of the file, and your file directory is obviously not in the same folder.

We can use the following code to provide relative paths. Of course, absolute paths are more commonly used.

import os
import sys
os.path.join(os.path.dirname(__file__), '../')
sys.path.append(os.path.join(os.path.dirname(__file__), '../'))
from utils import time
  • Related