如何在python中导入名称中带有空格的文件? [英] How do you import a file in python with spaces in the name?

查看:138
本文介绍了如何在python中导入名称中带有空格的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是否必须取出文件名中的所有空格才能导入它,或者有什么方法可以告诉 import 有空格?

Do I have to take out all the spaces in the file name to import it, or is there some way of telling import that there are spaces?

推荐答案

你应该去掉文件名中的空格.因为文件名被用作导入模块的标识符(即 foo.py 将被导入为 foo)并且 Python 标识符不能有空格,所以不支持通过 import 语句.

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.

如果你确实由于某种原因需要这样做,你可以使用__import__函数:

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

foo_bar = __import__("foo bar")

这会将 foo bar.py 导入为 foo_bar.这与 import 语句有点不同,你应该避免它.

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

这篇关于如何在python中导入名称中带有空格的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆