Home > Backend Development > Python Tutorial > How Can I Import Files from Non-Standard Locations in Python?

How Can I Import Files from Non-Standard Locations in Python?

DDD
Release: 2024-12-23 12:51:11
Original
668 people have browsed it

How Can I Import Files from Non-Standard Locations in Python?

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
Copy after login

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
Copy after login

With this modification, you can now import the function from file.py within some_file.py:

from file import func_name
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template