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 >>>
Which would make the answer "No, you can't. Rename the module to something that starts with a letter or an underscore."
If you have your own python files you want to import, you can use the import statement as follows: >>> import my_file # assuming you have the file, my_file.py in the current directory. # For files in other directories, provide path to that file, absolute or relative.
You could do
puzzle = __import__('8puzzle')
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.
The above answers are correct, but as for now, the recommended way is to use import_module
function:
importlib.import_module(name, package=None)
Import a module. The name argument specifies what module to import in absolute or relative terms (e.g. eitherpkg.mod
or..mod
). If the name is specified in relative terms, then the package argument must be set to the name of the package which is to act as the anchor for resolving the package name (e.g.import_module('..mod', 'pkg.subpkg')
will importpkg.mod
).The import_module() function acts as a simplifying wrapper around
importlib.__import__()
. This means all semantics of the function are derived fromimportlib.__import__()
. The most important difference between these two functions is thatimport_module()
returns the specified package or module (e.g.pkg.mod
), while__import__()
returns the top-level package or module (e.g.pkg
).If you are dynamically importing a module that was created since the interpreter began execution (e.g., created a Python source file), you may need to call
invalidate_caches()
in order for the new module to be noticed by the import system.
__import__
is not recommended now.
importlib.__import__(name, globals=None, locals=None, fromlist=(), level=0)
An implementation of the built-in__import__()
function.Note Programmatic importing of modules should use
import_module()
instead of this function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With