Home >Backend Development >Python Tutorial >How to Import a File from a Subdirectory in Python?

How to Import a File from a Subdirectory in Python?

Barbara Streisand
Barbara StreisandOriginal
2024-11-17 16:02:02192browse

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
  3. Optional Alternative:
    Alternatively, you can use the following import statement to alias the BoxTime module as BT:

    import lib.BoxTime as BT

    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!

Statement:
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