58

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?

Jeffrey Scofield
  • 65,646
  • 2
  • 72
  • 108
lilfrost
  • 590
  • 1
  • 4
  • 7
  • Could you show some code please? Normally Python has no problem with spaces in filenames. (Oh wait, unless you're talking about the `import` statement, in which case Python doesn't support spaces in module names.) – Greg Hewgill Feb 03 '12 at 04:06

4 Answers4

79

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.

Jeremy
  • 1
  • 85
  • 340
  • 366
12

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.

drevicko
  • 14,382
  • 15
  • 75
  • 97
  • 4
    Just to add, in Python 3 it would be [`exec(open("foo bar.py", "r").read())`](https://docs.python.org/3.3/whatsnew/3.0.html?highlight=execfile#builtins) – LHeng Sep 16 '19 at 12:22
  • 1
    This won't create a namespace for the module – Camion Jul 19 '20 at 18:34
  • `from foo_bar import *` likely doesn't behave the same as `execfile("foo_bar")` if foo_bar sets `__all__ = [...]` (which controls what is exported when using from the *-import – Tobias Bergkvist Oct 21 '21 at 10:56
9

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/3/library/importlib.html

gerrit
  • 24,025
  • 17
  • 97
  • 170
TBirkulosis
  • 581
  • 5
  • 8
4

Just to add to Banks' answer, if you are importing another file that you haven't saved in one of the directories Python checks for importing directories, you need to add the directory to your path with

import sys
sys.path.append("absolute/filepath/of/parent/directory/of/foo/bar")

before calling

foo_bar = __import__("foo bar")

or

foo_bar = importlib.import_module("foo bar")

This is something you don't have to do if you were importing it with import <module>, where Python will check the current directory for the module. If you are importing a module from the same directory, for example, use

import os,sys
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
foo_bar = __import__('foo_bar')

Hope this saves someone else trying to import their own weirdly named file or a Python file they downloaded manually some time :)

LHeng
  • 531
  • 5
  • 9