How to import module whose filename starts number

Y

Yong Hu

I have a few scripts whose file names start with numbers. For example, 01_step1.py, 02_step2.py

I tried to import them in another script by "import 01_step1" or "from 01_step1 import *". Both failed, saying "SyntaxError: invalid syntax"

Is there anyway to import those files? The file name must start with characters?
 
B

Benjamin Kaplan

I have a few scripts whose file names start with numbers. For example, 01_step1.py, 02_step2.py

I tried to import them in another script by "import 01_step1" or "from
01_step1 import *". Both failed, saying "SyntaxError: invalid syntax"
Is there anyway to import those files? The file name must start with characters?
--

I believe the restriction is that the module names must be valid
identifiers. You may still be able to import them using __import__ and then
assign the resulting module object to a valid name.
 
D

Dave Angel

I have a few scripts whose file names start with numbers. For example, 01_step1.py, 02_step2.py

I tried to import them in another script by "import 01_step1" or "from 01_step1 import *". Both failed, saying "SyntaxError: invalid syntax"

Is there anyway to import those files? The file name must start with characters?

A module name is like any other symbol in Python. It must start with a
letter (one of a hundred thousand or so), and have only letters or
digits within it. Plus underscore, and maybe a couple more special
characters.

mv would be your best bet. But if you HAVE to have a strange name, try
using the __import__() function.
 
P

Peter Otten

Yong said:
I have a few scripts whose file names start with numbers. For example,
01_step1.py, 02_step2.py

I tried to import them in another script by "import 01_step1" or "from
01_step1 import *". Both failed, saying "SyntaxError: invalid syntax"

Is there anyway to import those files? The file name must start with
characters?

Or an underscore. The module name must be a valid identifier. In CPython you
can hack around that restriction with

step01 = __import__("01_step1")

but this "solution" is not portable and I recommend that you rename your
scripts instead.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top