Python: Importing a File in the Same Directory
Python Import File in Same Directory
Python is a versatile programming language that offers numerous features and capabilities for developers. One particularly useful functionality we will explore in this tutorial is the ability to import files located in the same directory as our Python script. This is a common practice when organizing your code and making it more modular and reusable.
Step 1: Creating the File Structure
Before we dive into the code, let’s set up our file structure. Create a new directory on your machine and name it “my_project”. Inside this directory, create two files: “main.py” and “utils.py”. The “main.py” file will be our main script, and the “utils.py” file will contain some auxiliary functions that we want to import into our main script.
Step 2: Writing the Auxiliary Functions
Open the “utils.py” file and write the following code:
Here, we have defined two simple functions, add_numbers
and multiply_numbers
, which will perform addition and multiplication operations, respectively.
Step 3: Importing the Functions
Now, let’s move on to our main script in the “main.py” file. Open this file and ensure that the following code is included at the beginning:
In this line of code, we are using the from
keyword to specify the file “utils.py”, and importing the add_numbers
and multiply_numbers
functions from it. By doing so, we can access these functions directly in our main script.
Step 4: Using the Imported Functions
Now that we have imported the functions, let’s put them to use. In the “main.py” file, write the following code:
Here, we are calling the add_numbers
function with arguments 5 and 10 and storing the result in the variable result_1
. Similarly, we are calling the multiply_numbers
function with arguments 3 and 7 and storing the result in the variable result_2
. Finally, we are printing the results to the console.
Step 5: Running the Script
To execute our Python script, open a command prompt or terminal window and navigate to the “my_project” directory. Once inside the directory, run the following command:
You should see the following output:
Congratulations! You have successfully imported functions from a file located in the same directory and used them in your Python script.
Conclusion
In this tutorial, we have learned how to import files from the same directory in Python. By organizing your code into separate files and importing them when needed, you can enhance the modularity and reusability of your codebase. This is a fundamental concept that will prove useful as you continue your Python programming journey.
Continue practicing and exploring Python’s vast functionalities to become a proficient developer. Happy coding!