如何导入另一个目录中的文件?

时间:2019-12-09 21:51:57

标签: python python-3.x file

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

如何在insert_data.py中导入db.py? (我正在使用python 3)

3 个答案:

答案 0 :(得分:0)

from components import db

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

答案 1 :(得分:0)

  1. __init__.py放入components文件夹中
  2. 使用scriptsfrom ..components import db文件夹访问它

答案 2 :(得分:0)

有几种选择,它有助于了解Python的模块和软件包的工作方式(这并不总是完全简单明了的):

一种方法是在脚本的开头显式修改模块搜索路径:

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

Importing from a relative path in PythonExecution of Python code with -m option or not中所述,使用一种不太强悍的方式使用相对导入