Call a function from another file?

前端 未结 17 2751
梦谈多话
梦谈多话 2020-11-22 08:06

Set_up: I have a .py file for each function I need to use in a program.

In this program, I need to call the function from the external files.

I\'ve tried:

17条回答
  •  鱼传尺愫
    2020-11-22 08:52

    You can call the function from a different directory as well, in case you cannot or do not want to have the function in the same directory you are working. You can do this in two ways (perhaps there are more alternatives, but these are the ones that have worked for me).

    Alternative 1 Temporarily change your working directory

    import os
    
    os.chdir("**Put here the directory where you have the file with your function**")
    
    from file import function
    
    os.chdir("**Put here the directory where you were working**")
    

    Alternative 2 Add the directory where you have your function to sys.path

    import sys
    
    sys.path.append("**Put here the directory where you have the file with your function**")
    
    from file import function
    

提交回复
热议问题