How to Import a File from a Subdirectory in Python?

Barbara Streisand
Release: 2024-11-17 16:02:02
Original
126 people have browsed it

How to Import a File from a Subdirectory in Python?

Importing a File from a Subdirectory

Problem:

You have a Python file named tester.py located in the /project directory, and another file named BoxTime.py in a subdirectory called lib within the /project directory. Despite attempting to import BoxTime using the import command, you encounter an ImportError.

Solution:

To resolve this issue, follow the steps outlined in the Python Packaging Documentation (Section 6.4):

  1. Create an __init__.py File:
    Place a blank file named __init__.py in the lib subdirectory. This file indicates that the directory is a Python package, enabling Python to recognize it as a module.
  2. Adjust Import Statement:
    In tester.py, adjust the import statement to specify the full path to the BoxTime module:

    import lib.BoxTime
    Copy after login
  3. Optional Alternative:
    Alternatively, you can use the following import statement to alias the BoxTime module as BT:

    import lib.BoxTime as BT
    Copy after login

    This allows you to access BoxTime functions as BT.bt_function() instead of lib.BoxTime.bt_function().

The above is the detailed content of How to Import a File from a Subdirectory 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