How to import another python script (.py) into main python file

前端 未结 2 1914
半阙折子戏
半阙折子戏 2021-01-05 07:40

is there a way to import multiple python files into a main python file?

I have a bunch of py files and each one has to run in the main python file and the data are s

相关标签:
2条回答
  • 2021-01-05 08:01

    The syntax for importing your_filename.py, assuming it is in the same directory, is

    import your_filename
    

    In your case, it would be

    import light
    

    Note the absence of .py.

    If your file is in a different directory, you'll need to do:

    import sys
    sys.path.append('path/to/dir/containing/your_filename.py')
    import your_filename
    

    Note that appending to sys.path is dangerous, and should not be done unless you know what you're doing.

    Read more at the official docs for import.

    0 讨论(0)
  • 2021-01-05 08:03

    To include the dictionary, you could do this if your file location is in different directory (with caution of path.append as @Coldspeed mentioned):

    import sys
    sys.path.append("path/foo/bar/")
    from light import *
    

    If it is in same directory as current directory, you could just do:

    from light import *
    
    0 讨论(0)
提交回复
热议问题