0

I've been working on a project that creates its own .py files that store handlers for the method, I've been trying to figure out how to store the Python files in folder and open them. Here is the code I'm using to create the files if they don't already exist, then importing the file:

if os.path.isfile("Btn"+ str(self.ButtonSet[self.IntBtnID].IntPID) +".py") == False:
        TestPy = open("Btn"+ str(self.ButtonSet[self.IntBtnID].IntPID) +".py","w+")
        try:
            TestPy.write(StrHandler)
        except Exception as Error:
            print(Error)
        TestPy.close()
    self.ButtonSet[self.IntBtnID].ImpHandler = __import__("Btn" + str(self.IntBtnID))
    self.IntBtnID += 1

when I change this line:

self.ButtonSet[self.IntBtnID].ImpHandler = __import__("Btn" + str(self.IntBtnID))

to this:

self.ButtonSet[self.IntBtnID].ImpHandler = __import__("Buttons\\Btn" + str(self.IntBtnID))

the fill can't be found and ends up throwing an error because it can't find the file in the folder.

Do know why it doesn't work I just don't know how to get around the issue:/

My question is how do I open the .py when its stored in a folder?

Dharman
  • 30,962
  • 25
  • 85
  • 135
Kyle Burns
  • 157
  • 2
  • 15

3 Answers3

2

There are a couple of unidiomatic things in your code that may be the cause of your issue. First of all, it is generally better to use the functions in os.path to manipulate paths to files. From your backslash usage, it appears you're working on Windows, but the os.path module ensures consistent behaviour across all platforms.

Also there is importlib.import_module, which is usually recommended over __import__. Furthermore, in case you want to load the generated module more than once during the lifetime of your program, you have to do that explicitly using imp.reload.

One last tip: I'd factor out the module path to avoid having to change it in more than one place.

Emilia Bopp
  • 866
  • 10
  • 20
1

You can't reference a path directory when you are importing files. Instead, you want to add the directory to your path and then import the name of the module.

import sys
sys.path.append( "Buttons" )
__import__("Btn"+str(self.IntBtnId))

See this so question for more information.

Community
  • 1
  • 1
amccormack
  • 13,207
  • 10
  • 38
  • 61
1

The first argument to the __import__() function is the name of the module, not a path to it. Therefore I think you need to use:

self.ButtonSet[self.IntBtnID].ImpHandler = __import__("Buttons.Btn" + str(self.IntBtnID))

You may also need to put an empty __init__.py file in the Buttons folder to indicate it's a package of modules.

martineau
  • 119,623
  • 25
  • 170
  • 301