I have a directory called WeatherApp, and inside I have two directories called weathermap and tests. I have weathermap.py file inside a weathermap directory. I have a init.py file inside the weathermap directory as well. I am trying to import the file to test.py file in tests directory and I have a following code.
import os
import pprint
from weathermap.weathermap import Weather
from dotenv import load_dotenv
# Load the contents of the .env file into the environment variables
load_dotenv()
openweather_api = os.getenv('OPENWEATHER_API')
help(Weather)
The code works perfectly in Pycharm without any error. But, when I run same file in VSCode I get a following error:
ModuleNotFoundError Traceback (most recent call last)
Cell In[1], line 2
1 import pprint
----> 2 from weathermap.weathermap import Weather
3 from dotenv import load_dotenv
5 # Load the contents of the .env file into the environment variables
ModuleNotFoundError: No module named 'weathermap'
I had to include a following code to make it run inside the VSCode.
import sys
import os
# Get the current directory of the test.py file
current_directory = os.getcwd()
# Add the parent directory (weatherapp) to the Python path
parent_directory = os.path.abspath(os.path.join(current_directory, '..'))
sys.path.append(parent_directory)
When I sys.path.append(parent_directory)
, the code works. I want to know what is the right way to import the module in the python when files are in different directory. And does pycharm has special functionality that allows it to locate directory without any extra code?