How do you import a file in python with spaces in the name?

廉价感情. 提交于 2019-11-27 07:35:05

You should take the spaces out of the filename. Because the filename is used as the identifier for imported modules (i.e. foo.py will be imported as foo) and Python identifiers can't have spaces, this isn't supported by the import statement.

If you really need to do this for some reason, you can use the __import__ function:

foo_bar = __import__("foo bar")

This will import foo bar.py as foo_bar. This behaves a little bit different than the import statement and you should avoid it.

If you want to do something like from foo_bar import * (but with a space instead of an underscore), you can use execfile (docs here):

execfile("foo bar.py")

though it's better practice to avoid spaces in source file names.

You can also use importlib.import_module function, which is a wrapper around __import__.

foo_bar_mod = importlib.import_module("foo bar")

or

foo_bar_mod = importlib.import_module("path.to.foo bar")

More info: https://docs.python.org/2/library/importlib.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!