pythonimport

How to import from filename that starts with a number


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 any way 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
>>> 

Solution

  • 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.

    12 years later...

    See answer below (use importlib.import_module from Python 3.1) for interoperability and understandability.

    https://docs.python.org/3/library/importlib.html#importlib.import_module

    This provides an implementation of import which is portable to any Python interpreter. This also provides an implementation which is easier to comprehend than one implemented in a programming language other than Python.

    ....

    The import_module() function acts as a simplifying wrapper around importlib.__import__(). This means all semantics of the function are derived from importlib.__import__(). The most important difference between these two functions is that import_module() returns the specified package or module (e.g. pkg.mod), while __import__() returns the top-level package or module (e.g. pkg).