1

I need to import a python file from another folder. To do that I am using the following lines of code

import sys
sys.path.insert(0, '/home/mininet/Sandbox/mapper')
from parser import read-dir

I get a syntax error because my python file name has a "-" character

from parser import read-dir
                       ^
SyntaxError: invalid syntax

Is there any way to get around it?

brokendreams
  • 827
  • 2
  • 10
  • 29
  • Refer http://stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path –  Nov 06 '15 at 22:43
  • 2
    Can you rename the file? `read-dir` isn't a valid variable name (it's a subtraction expression), but `read_dir` would be. – Blckknght Nov 06 '15 at 22:52

1 Answers1

4

Because your file has - character in file name. Instead of import, use __import__ or importlib.

For example, I have a script called h-e-l-l-o.py:

>>> import h-e-l-l-o
  File "<input>", line 1
    import h-e-l-l-o
            ^
SyntaxError: invalid syntax


>>> import importlib
>>> importlib.import_module('h-e-l-l-o')
<module 'h-e-l-l-o' from '/home/kevin/h-e-l-l-o.py'>


>>> __import__('h-e-l-l-o')
<module 'h-e-l-l-o' from '/home/kevin/h-e-l-l-o.py'>
>>> 
Remi Guan
  • 21,506
  • 17
  • 64
  • 87