[ACCEPTED]-Why am I getting the following error in Python "ImportError: No module named py"?-python

Accepted answer
Score: 44

Instead of:

import test.py

simply write:

import test

This assumes test.py 2 is in the same directory as the file that 1 imports it.

Score: 7

This strange-looking error is a result of 7 how Python imports modules.

Python sees:

import test.py

Python thinks (simplified 6 a bit):

import module test.

  • search for a test.py in the module search paths
  • execute test.py (where you get your output)
  • import 'test' as name into current namespace

import test.py

  • search for file test/py.py
  • throw ImportError (no module named 'py') found.

Because 5 python allows dotted module names, it just 4 thinks you have a submodule named py within 3 the test module, and tried to find that. It 2 has no idea you're attempting to import 1 a file.

Score: 5

You don't specify the extension when importing. Just 1 do:

import test
Score: 2

As others have mentioned, you don't need 11 to put the file extension in your import 10 statement. Recommended reading is the Modules section of the Python Tutorial.

For 9 a little more background into the error, the 8 interpreter thinks you're trying to import 7 a module named py from inside the test package, since 6 the dot indicates encapsulation. Because 5 no such module exists (and test isn't even a package!), it raises 4 that error.

As indicated in the more in-depth documentation on the import statement it still 3 executes all the statements in the test module 2 before attempting to import the py module, which 1 is why you get the values printed out.

More Related questions