To import a class from another file in Python, use the sys.path.append() method. The sys.path.append() is a built-in method with a path variable to add a specific path for interpreters to search. It accepts the path as an argument.
To import files from a different folder, add the Python path at runtime. To add the Python path, use the sys.path.append() method, which includes locations such as the package. You need to add Python path runtime using the sys.path.append() method will then resolve the importing file’s path.
Importing files from one folder to another in Python is a tricky task, and by default, you can’t do that, and if you try, you will get an error. The reason is that Python only searches the directory from which the entry-point script is running.
The sys is a built-in module that contains parameters specific to the system.
Example of importing a class in Python
In our current working project directory, there is a folder called libs, and inside that folder is one Python file called add.py.
We want to use this add.py file in our app.py file.
Write the following code inside the add.py file.
def sum(x, y): return x + y
As the name suggests, it will return the addition of two numbers.
Open our main program file, app.py, and add the following code.
import sys sys.path.append("/Users/krunal/Desktop/code/pyt/database/libs")
Here, we are appending the path runtime using the sys.path.append() method and pass the destination path where we have put our class file add.py.
Now, we can import the add.py file since now Python interpreter will know where to look for a class file.
import sys sys.path.append("/Users/krunal/Desktop/code/pyt/database/libs") from add import sum
We are importing the sum() function directly from the add module.
import sys sys.path.append("/Users/krunal/Desktop/code/pyt/database/libs") from add import sum print(sum(5, 6))
That is it. We successfully imported a file into our program and used it perfectly.
This approach works fine when you want to import from a “sibling” directory, so one up, one down.
Importing class from a package in Python
To import a class from a package, use the following code.
from application.app.folder.file import function_name
Please make sure that the package folder contains an __init__.py, which allows it to be included as a package.
But when it is necessary to modify the Python path, you need to use the above approach and not use it.
If you structure your files like packages, this approach will be effective. Otherwise, the first approach will be very much helpful. Use according to your requirements.
So, this is how you need to import a file from one directory to another or one class from another class.
That is it.