To import Python scripts (modules) into another Python script, you can use the import statement. Here’s how to do it:
Basic Import
-
Same Directory: If the script you want to import is in the same directory as your current script, you can simply use:
import script_nameReplace
script_namewith the name of the Python file (without the.pyextension). -
Using Functions or Classes: After importing, you can access functions or classes defined in that script using the dot notation:
script_name.function_name()
Example:
Assuming you have a script named math_utils.py with a function add:
# math_utils.py
def add(a, b):
return a + b
You can import and use it in another script:
# main.py
import math_utils
result = math_utils.add(5, 3)
print(result) # Output: 8
Importing Specific Functions or Classes
If you only need specific functions or classes, you can import them directly:
from script_name import function_name
Example:
from math_utils import add
result = add(5, 3)
print(result) # Output: 8
Importing All Functions
You can also import everything from a module using:
from script_name import *
However, this is generally discouraged as it can lead to confusion with variable names.
Importing from Subdirectories
If your script is in a subdirectory (package), you may need to use:
from package_name import script_name
Conclusion
Using the import statement allows you to organize your code into reusable modules, making it easier to manage larger projects. If you have more questions or need further examples, feel free to ask!
