Search code examples
pythonmodulepython-importimporterrorpythoninterpreter

Python script correctly executes every statement, but also returns ModuleNotFoundError


I'm running my Python script in Terminal on MacOS.

The script1.py source code:

# A first Python script
import sys              # Load a library module
print(sys.platform)         
print(2 ** 100)             # Raise 2 to a power
x = 'Spam!'
print(x * 8)                # String repetition

The output in the Python interactive session:

>>> import script1.py
darwin
1267650600228229401496703205376
Spam!Spam!Spam!Spam!Spam!Spam!Spam!Spam!
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'script1.py'; 'script1' is not a package

All the statements in the script are executed correctly, but the interpreter returns an error that says the script can't be found.

What's going on here?


Solution

  • import script1.py
    

    The interpreter is thinking you're trying to import the module named py from inside the package script1.

    Now, it can find a file called script1 - that's your file called script1.py. So it goes ahead and loads it. And "loading" for python means running the statements inside the file. So it does that. And you get your output.

    Then the interpreter realizes that it was expecting py to be a module, so script1 should've been a package (i.e. a directory with source files inside it). But script1 was just an ordinary file. Hence it throws that error.

    When trying to import a module named script1.py, you should use:

    import script1
    

    When trying to run a file called script1.py, you may use:

    python script.py