简体   繁体   中英

How do I import a file that is in another directory?

-Booking
    -components
        -db.py
    -scripts
        -insert_data.py

How do I import db.py in insert_data.py? (I'm using python 3)

from components import db

只要components有(可能为空) __init__.py就可以工作

  1. Put __init__.py inside components folder
  2. Access it from scripts folder using from ..components import db

There are several options, and it helps to know how Python's modules and packages work (which is not always completely straightforward and intuitive):

One way is to explicitly modify the module search path in the beginning of your script:

import sys, os
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'components'))
import db

A less hacky way uses relative import , as described in Importing from a relative path in Python and Execution of Python code with -m option or not .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM