Import Modules From Another Folder in Python


There are multiple ways to import modules from another folder in Python. Here are some of them:

  • Add the folder to the system path: You can add the folder containing the module to the system path using the sys module. This will allow you to import the module as if it were in the same folder as your script. Here's an example:
   import sys
   sys.path.insert(0, '/path/to/folder')
   import module_name

Replace /path/to/folder with the actual path to the folder containing the module, and module_name with the name of the module you want to import.

  • Use relative imports: If the module you want to import is in a subfolder of your script's folder, you can use relative imports. Here's an example:
   from .subfolder import module_name

The . before subfolder indicates that it's a relative import. Replace subfolder with the actual name of the subfolder, and module_name with the name of the module you want to import.

  • Use the imp module: The imp module provides a low-level interface for importing modules. Here's an example:
   import imp
   module_name = imp.load_source('module_name', '/path/to/folder/module_name.py')

Replace module_name with the actual name of the module, and /path/to/folder/module_name.py with the actual path to the module.

Note that it's generally not recommended to import modules from outside your script's folder, as it can make your code harder to understand and maintain. If possible, it's better to organize your code into packages and modules within your script's folder.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.