How can I source a Python file from another Python file?

PythonServer Side ProgrammingProgramming

In order to source a Python file from another python file, you have to use it like a module. import the file you want to run and run its functions. For example, say you want to import fileB.py into fileA.py, assuming the files are in the same directory, inside fileA you'd write

import fileB

Now in fileA, you can call any function inside fileB like:

fileB.my_func()

In file B you have to define a function called my_func before you can use it in any other file.

Example

def my_func():
    print("Hello from B")

Output

Now when you run fileA.py, you will get the output:

Hello from B
raja
Published on 26-Dec-2017 16:51:00
Advertisements