Search code examples
pythonfilesyntaximportexecute

python file import another python file, prompts error


I'm on mac using python2.7 and I have 2 python files under same directory

$ls *.py
1p.py 2.py

And they're very simple:

$cat 1p.py
def f():
    print "hello"

$cat 2.py
import 1p
f()

But running 2.py failed:

$python 2.py
File "2.py", line 1
    import 1p
        ^
SyntaxError: invalid syntax

Do I need to setup and env variable, or to change my program? Thanks


Solution

  • In order to be imported, module names, and thus file names must be valid python identifiers. So even if your filesystem accepts the name, it's not enough.

    An identifier like 1p isn't valid, you have to rename your module file. Why not p1.py instead? That would work.