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

前端 未结 4 1745
鱼传尺愫
鱼传尺愫 2020-11-27 17:09

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?

4条回答
  •  感动是毒
    2020-11-27 17:22

    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 , 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 :)

提交回复
热议问题