1

I am wondering why Python does not find modules in the same folder when code is run in a cell. I use Spyder and when I run a cell

#%% import cell

from gym import Env
from gym.spaces import Discrete, Box, Tuple
import numpy as np
import random
import pandas as pd
import Run_Simulations
import SetUpScenarios

I get the error messages that the modules Run_Simulations and SetUpScenarios are not found altough they are in the same folder. Strangely when not running the single cell but the whole code (where there are no other import instructions or anything similar), the modules can be found and are correctly imported.

PeterBe
  • 700
  • 1
  • 17
  • 37
  • By default Spyder runs the script using the directory where this script is located as the default working directory. If you run just the cell, you are using the working directory that is set at that exact moment. Is it possible you are using a working directory different than the directory where your script is located? – xgsktx Aug 25 '21 at 11:54
  • Thanks for your answer xgsktx. How can I find out where my working directory is? – PeterBe Aug 25 '21 at 12:20
  • `import os` and then `os.getcwd()`. If you want to change your working directory, you can also do `os.chdir("your_directory")`. – xgsktx Aug 26 '21 at 05:22
  • Thanks for your answer. Basically I checked and my working directory is different from the folder where the script is in. Is it advisable to change that? Do I have to change the working directory to every subfolder where my python files are saved in? – PeterBe Aug 26 '21 at 08:44
  • If the modules you are trying to import are modules you frequently use, you should consider adding the directory where these are saved to your PYTHONPATH. Check out this [thread](https://stackoverflow.com/questions/3402168/permanently-add-a-directory-to-pythonpath) for additional help with that. Another option would be to add the complete path of the modules in your import statement. – xgsktx Aug 26 '21 at 10:47
  • Thanks xgsktx. But I still do not really understand why it is no problem when I run the whole code while running a single cell is a problem. – PeterBe Aug 27 '21 at 06:44
  • @xgsktx: Thanks for your answers. You wrote "If you run just the cell, you are using the working directory that is set at that exact moment. " ---> What does that mean? – PeterBe Sep 02 '21 at 11:46

0 Answers0