Home >Backend Development >Python Tutorial >How Can I Import a Module from a Different Directory in Python?
Importing External Modules from a Different Directory
You're encountering difficulties importing a function from a specific file in one directory into another file located in a different directory. Despite using the syntax from application.app.folder.file import func_name, the import fails.
Understanding Python's Module Search Path
By default, Python searches for modules (i.e., files containing functions and classes) in:
Your attempt to import a file from a different directory failed because the target file is not in any of those search paths.
Altering the Module Search Path
To resolve this, you can dynamically add the directory containing the target file to sys.path. This will make Python aware of the new location for importing modules.
Adding the Directory to sys.path
In the file where you want to import the function (some_file.py in your case), add the following line to the beginning of the file:
import sys # sys.path[0] is reserved for the script path, so insert the new path at index 1 sys.path.insert(1, "/path/to/application/app/folder")
This line inserts the specified directory path into sys.path, telling Python to search for modules in that directory as well.
Importing the Module
After adding the directory to sys.path, you can import the module (file.py in your case) as follows:
import file
The above is the detailed content of How Can I Import a Module from a Different Directory in Python?. For more information, please follow other related articles on the PHP Chinese website!