pythonimportfilenamesspaces

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


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?


Solution

  • 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.