Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In python, how to import filename starts with a number

Tags:

python

import

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 >>>  
like image 724
Simon Guo Avatar asked Feb 01 '12 02:02

Simon Guo


People also ask

Can Python name start with number?

Which would make the answer "No, you can't. Rename the module to something that starts with a letter or an underscore."

How do I import a specific file into Python?

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.


2 Answers

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.

like image 65
Yuji 'Tomita' Tomita Avatar answered Sep 28 '22 03:09

Yuji 'Tomita' Tomita


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. either pkg.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 import pkg.mod).

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

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.

like image 45
laike9m Avatar answered Sep 28 '22 05:09

laike9m