How to load all modules in a folder?

后端 未结 18 1912
失恋的感觉
失恋的感觉 2020-11-22 05:37

Could someone provide me with a good way of importing a whole directory of modules?
I have a structure like this:

/Foo
    bar.py
    spam.py
    eggs.py         


        
18条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 06:29

    Python, include all files under a directory:

    For newbies who just can't get it to work who need their hands held.

    1. Make a folder /home/el/foo and make a file main.py under /home/el/foo Put this code in there:

      from hellokitty import *
      spam.spamfunc()
      ham.hamfunc()
      
    2. Make a directory /home/el/foo/hellokitty

    3. Make a file __init__.py under /home/el/foo/hellokitty and put this code in there:

      __all__ = ["spam", "ham"]
      
    4. Make two python files: spam.py and ham.py under /home/el/foo/hellokitty

    5. Define a function inside spam.py:

      def spamfunc():
        print("Spammity spam")
      
    6. Define a function inside ham.py:

      def hamfunc():
        print("Upgrade from baloney")
      
    7. Run it:

      el@apollo:/home/el/foo$ python main.py 
      spammity spam
      Upgrade from baloney
      

提交回复
热议问题