Importing a specific function from a file with a space in its name

I am trying to import just one function from a .py file which has a space in its title. Due to external constraints, I cannot rename the file.

My first try was:

from File 1 import my_func

But that got a SyntaxError. Following advice on other StackOverflow, I found ways to import all the functions from a module/file:




globals().update(vars(__import__('File 1')))

However, I would like to only import my_func. I would also prefer to do this without using other modules like importlib. Any help is very much appreciated, I am still learning!


  • Editing the answer as requsted:
    Source: How do you import a file in python with spaces in the name?.

    Importing single function from a module with spaces in name without using importlib is simply impossible, since your only weapon here is __import__.

    Your only option is to import the whole module and only keep functions you like. But it still imports the whole module.

    Important notice

    Getting rid of spaces and other non-alphanumeric symbols from module names is strongly recommended.



    def foo():
    def spam():
        print("Get out!")

    globals()["foo"] = getattr(__import__("File 1"),"foo")