How to implement the import module of different levels of directories in python

Source: Internet
Author: User
Tags parent directory in python


Third-party module packages are often used for programming using python. You can use python setup install to install this package and import it through import XXX or from XXX import yyy. However, if the dependency package is self-written and you do not want to install it in the corresponding directory of python, you can put it in this directory for import calling. To clarify the relationship between programs more clearly, for example, we will put this package in the lib directory and then call it. This article summarizes common module call methods.

1. You can call

The program structure is as follows:

-- Src
| -- Mod1.py
| -- Test1.py

If you import the module mod1 in the test1.py program, use

Import mod1
Or
From mod1 import *;

2. Call the modules in the subdirectory

The program structure is as follows:

-- Src
| -- Mod1.py
| -- Lib
| -- Mod2.py
| -- Test1.py
The test1.py and lib directories (parent directory of mod2.py) are displayed. If you want to import module mod2.py to test1.py, you can create an empty file _ init _ in the lib folder __. py file (you can also customize the output module interface in this file), and then use:

From lib. mod2 import *
Or
Import lib. mod2.

3. Call files under the parent directory

The program structure is as follows:

-- Src
| -- Mod1.py
| -- Lib
| -- Mod2.py
| -- Sub
| -- Test2.py

Here we want to implement test2.py to call mod1.py and mod2.py. The practice is to jump to the src directory and call mod1 directly, and then create an empty file _ init _ in lib __. you can use the import lib. mod2 is called. The code is as follows:

Import sys
Sys. path. append ("..")
Import mod1
Import mod2.mod2

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.