tags:

views:

595

answers:

4

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!

+4  A: 

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

import test
Evan Fosmark
+7  A: 

Instead of:

import test.py

simply write:

import test

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

DzinX
+2  A: 

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.

cdleary
+2  A: 

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.

Triptych
I think the terminology is technically "*module* named `py` within the `test` *package*". (Could be wrong, though!)
cdleary