Call a function from another file?

前端 未结 17 2392
梦谈多话
梦谈多话 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:45

    Came across the same feature but I had to do the below to make it work.

    If you are seeing 'ModuleNotFoundError: No module named', you probably need the dot(.) in front of the filename as below;

    from .file import funtion

    0 讨论(0)
  • 2020-11-22 08:45

    append a dot(.) in front of a file name if you want to import this file which is in the same directory where you are running your code.

    For example, i'm running a file named a.py and i want to import a method named addFun which is written in b.py, and b.py is there in the same directory

    from .b import addFun

    0 讨论(0)
  • 2020-11-22 08:46

    Any of the above solutions didn't work for me. I got ModuleNotFoundError: No module named whtever error. So my solution was importing like below

    from . import filename # without .py  
    

    inside my first file I have defined function fun like below

    # file name is firstFile.py
    def fun():
      print('this is fun')
    

    inside the second file lets say I want to call the function fun

    from . import firstFile
    
    def secondFunc():
       firstFile.fun() # calling `fun` from the first file
    
    secondFunc() # calling the function `secondFunc` 
    
    0 讨论(0)
  • 2020-11-22 08:49

    You can do this in 2 ways. First is just to import the specific function you want from file.py. To do this use

    from file import function
    

    Another way is to import the entire file

    import file as fl
    

    Then you can call any function inside file.py using

    fl.function(a,b)
    
    0 讨论(0)
  • 2020-11-22 08:49

    You should have the file at the same location as that of the Python files you are trying to import. Also 'from file import function' is enough.

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题