【问题标题】:Cannot import file because of file name由于文件名无法导入文件
【发布时间】:2016-02-08 04:34:58
【问题描述】:

我需要从另一个文件夹导入一个 python 文件。为此,我使用以下代码行

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

我收到一个语法错误,因为我的 python 文件名有一个“-”字符

from parser import read-dir
                       ^
SyntaxError: invalid syntax

有什么办法可以解决吗?

【问题讨论】:

标签: python python-2.7 python-3.x import


【解决方案1】:

因为您的文件在文件名中有- 字符。代替import,使用__import__importlib

例如,我有一个名为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'>
>>> 

【讨论】:

    猜你喜欢
    • 2019-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-06
    • 2013-03-03
    • 2014-05-30
    • 2020-03-25
    • 2021-12-28
    相关资源
    最近更新 更多