jtbradle
jtbradle

Reputation: 2508

Why am I getting the following error in Python "ImportError: No module named py"?

I'm a Python newbie, so bear with me :)

I created a file called test.py with the contents as follows:

test.py
import sys
print sys.platform
print 2 ** 100

I then ran import test.py file in the interpreter to follow an example in my book. When I do this, I get the output with the import error on the end.

win32
1267650600228229401496703205376
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named py

Why do I get this error and how do I fix it? Thanks!

Upvotes: 23

Views: 44289

Answers (4)

cdleary
cdleary

Reputation: 71424

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

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

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

Upvotes: 3

Kenan Banks
Kenan Banks

Reputation: 211980

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

Python sees:

import test.py

Python thinks (simplified 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 python allows dotted module names, it just thinks you have a submodule named py within the test module, and tried to find that. It has no idea you're attempting to import a file.

Upvotes: 8

Dzinx
Dzinx

Reputation: 57804

Instead of:

import test.py

simply write:

import test

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

Upvotes: 45

Evan Fosmark
Evan Fosmark

Reputation: 101691

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

import test

Upvotes: 6

Related Questions