Python module calls between different directories

Source: Internet
Author: User

Sometimes the calling module is no longer the same directory. Direct import is not loaded in. The default load path is the path specified in Sys.path. If you want to specify the directory to be loaded, you need to add this directory to Sys.path.

For example, to load a module in the parent directory's sibling directory.

Current file atm.py the module to be loaded settings.py

1. Find the absolute path of the current file first

Import Osprint (Os.path.abspath (__file__)) #abspath returns the absolute path of the file, the equivalent path of the __file__ file

2. Find the parent directory

Import Osprint (Os.path.dirname (Os.path.dirname (Os.path.abspath (__file__))) #E: \PYWWW\DAY04\ATM

3. Add Environment variables

Import Osimport Sysbase_dir = Os.path.dirname (Os.path.dirname (Os.path.abspath (__file__))) Sys.path.append (Base_dir) #

5. Loading module

settings.py Code:

def main ():    print (' main ')

Python module calls between different directories

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.