Basically there is a file called 8puzzle.py
and I want to import the file into another file (in the same folder and I cannot change the file name as the file is provided). Is there anyway to do this in Python? I tried usual way from 8puzzle import *
, it gives me an error.
Error is:
>>> import 8puzzle
File "<input>", line 1
import 8puzzle
^
SyntaxError: invalid syntax
>>>
You could do
Very interesting problem. I'll remember not to name anything with a number.
If you'd like to
import *
-- you should check out this question and answer.Don't use the
.py
extension in your imports.Does
from 8puzzle import *
work?For what it's worth,
from x import *
is not a preferred Python pattern, as it bleeds that module's namespace into your current context.In general, try to import things you specifically want from that module. Any global from the other module can be imported.
e.g., if you have
8puzzle.foo
you could do `from 8puzzle importEdit:
While my
.py
message is correct, it isn't sufficient.The other poster's
__import__('8puzzle')
suggestion is correct. However, I highly recommend avoiding this pattern.For one, it's reserved an internal, private Python method. You are basically breaking the fundamental assumptions of what it means to be able to import a module. Simply renaming the file to something else, like
puzzle8
, will remedy this.This will frustrate the hell out of experienced Python programmers who are expecting to know what your imports are at the top and are expecting code to (try to) conform to PEP8.
The above answers are correct, but as for now, the recommended way is to use
import_module
function:__import__
is not recommended now.