There are various libraries and functionalities that come with Python, and sometimes, you may need to import one Python file into another.
In this tutorial, we will guide you on how to import a Python file into another Python file.
Step 1: Create The File To Be Imported
Before we can import a Python file into another, we need to create the file that we want to import.
You can use any Python editor or IDE of your choice to create the file, and it should have a .py extension. Ensure that the file contains the functions or modules that you want to import into another file.
Step 2: Create The File To Import The First File
In this step, we need to create the file that will import the first file. Open a new file in the same directory as the first file and ensure that it also has a .py extension.
This file will act as the main file and will use the functions and modules in the first file.
Step 3: Import The First File Into The Second File
Now that we have both files, we can proceed to import the first file into the second file. To do that, we will use the import function followed by the name of the file without the .py extension.
For example, if the file to be imported is named “file_to_be_imported.py”, we will use the following code:
1 |
import file_to_be_imported |
Step 4: Use The Functions Or Modules From The Imported File
Now that we have imported the first file into the second file, we can use the functions or modules from the first file.
To use a function, we will call it using the name of the imported file followed by a dot and the name of the function.
For example, if the function to be used is named “function_to_be_used()”, we will use the following code:
1 2 |
import file_to_be_imported file_to_be_imported.function_to_be_used() |
Example Code:
Here is an example of a file named “file_to_be_imported.py” that contains a function named “greeting()”:
1 2 |
def greeting(name): print("Hello, " + name) |
Here is an example of a file named “main_file.py” that imports the “file_to_be_imported.py” file and uses the “greeting()” function:
1 2 |
import file_to_be_imported file_to_be_imported.greeting("John") |
Run the “main_file.py” file to see the output:
Hello, John
Conclusion:
Importing one Python file into another Python file is a simple process that allows you to reuse code and improve the functionality of your programs. By following the above steps and using the right syntax, you can easily import your Python files and leverage their functions and modules.