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

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.

Leave a Comment