Home > Backend Development > Python Tutorial > How to Import Modules from Subdirectories in Python?

How to Import Modules from Subdirectories in Python?

Susan Sarandon
Release: 2024-11-23 15:55:19
Original
795 people have browsed it

How to Import Modules from Subdirectories in Python?

Importing Files from Subdirectories

Importing external modules is a common practice in Python development. However, when the module resides in a subdirectory, importing it requires a specific approach.

Problem Statement

Suppose you have a file named tester.py located in the /project directory. This directory contains a subdirectory called lib, which houses a file named BoxTime.py. Your goal is to import BoxTime into tester.py.

Initial Attempt and Error

You attempted to import BoxTime using the following code:

import lib.BoxTime
Copy after login
Copy after login

However, this resulted in an ImportError, as Python could not find the module named lib.BoxTime.

Solution: Implementing a Package

To resolve this issue, you need to convert the lib directory into a Python package. This involves creating an empty file named __init__.py inside the lib directory.

/project
    /tester.py
    /lib/__init__.py
    /lib/BoxTime.py
Copy after login

This __init__.py file acts as a package initializer, informing Python that the directory is a package containing Python modules.

Importing the Module Correctly

Once the __init__.py file is in place, you can import BoxTime using either of the following methods:

import lib.BoxTime
Copy after login
Copy after login

or

import lib.BoxTime as BT
BT.bt_function()
Copy after login

The second method assigns BoxTime to the variable BT, allowing you to access its functions using the shorter alias.

The above is the detailed content of How to Import Modules from Subdirectories 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template