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

lilfrost picture lilfrost · Feb 3, 2012 · Viewed 31.3k times · Source

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?

Answer

Jeremy picture Jeremy · Feb 3, 2012

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.