Importing Files from Non-Standard Locations
This question addresses the issue of importing a file from a non-standard location. When importing a file, Python typically searches the directory where the entry-point script is running and the system path. To import a file from a location outside this search path, a modification to the Python path at runtime is necessary.
Here's the specific solution:
In the import statement, the path to the desired file must be specified explicitly. For example, in the given scenario:
from application.app.folder.file import func_name
However, this approach may not always be convenient or tenable. Instead, you can add the desired path to the Python path at runtime:
# some_file.py import sys # caution: path[0] is reserved for script path (or '' in REPL) sys.path.insert(1, '/path/to/application/app/folder') import file
With this modification, you can now import the function from file.py within some_file.py:
from file import func_name
Note: This approach is recommended only for specific use cases. Generally, it's preferable to structure your files into packages to avoid the need for manually modifying the Python path.
The above is the detailed content of How Can I Import Files from Non-Standard Locations in Python?. For more information, please follow other related articles on the PHP Chinese website!