-1

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?

  • Your problem is that you're running from a different directory in VSCode than you are in Pycharm. If they match, they should run the same. Perhaps something like [this](https://stackoverflow.com/a/56091981/12479639)? – Axe319 Aug 04 '23 at 18:59
  • why are you running YOUR script inside the `weathermap` module – rioV8 Aug 04 '23 at 19:36
  • Hello, thank you for your comments. I have a GitHub repo called weather app, and inside, I have two folders called weathermap and tests. I have a file called weathermap.py inside weathermap folder, which I am trying to import into my test.py file inside the tests folder. My code works in Pycharm but does not work in the VS code, so I am just wondering what I am doing wrong. – Savan Patel Aug 05 '23 at 02:04
  • As two different pieces of software, it's normal to have differences between them. Vscode uses the currently opened folder as the workspace, you may need to add additional pythonpath to ensure that the imported package can be used correctly. Like you mentioned. – JialeDu Aug 07 '23 at 06:20

0 Answers0