Search code examples
pythonpython-3.xminiconda

ImportError: No module named temperature from the terminal


I have miniconda installed and running various versions of python in different environments. I've created a temperature.py file and saved it in a folder called python in my root directory: /Users/name

When I type python on the terminal and then run import temperature.py from the terminal I get this error:

ImportError: No module named 'temperature'

Where should I have saved the temperature.py file?


Solution

  • The first place Python looks for modules to import is the working directory (i.e. the the directory of if you passed a script to python) or if you just launched python without a script, the directory you were in when you opened python. Failing to find it there, it uses the PYTHONPATH variable and if not found there either, it uses the a path specified in the installation of Python.

    At runtime you can check with sys.path the actual paths it is looking in.

    import sys
    print(sys.path)
    

    And you can even modify sys.path if you need to. Add to the beginning as that is the place import will look first:

    import sys
    sys.path.insert(0, <path_of_temperature.py>)
    

    Source https://docs.python.org/3/tutorial/modules.html

    6.1.2. The Module Search Path

    When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. sys.path is initialized from these locations:

    1. The directory containing the input script (or the current directory when no file is specified).
    2. PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
    3. The installation-dependent default.