如何导入另一个目录中的文件? [英] How do I import a file that is in another directory?

查看:121
本文介绍了如何导入另一个目录中的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

推荐答案

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

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

  • What's the difference between a Python module and a Python package?
  • What is __init__.py for?
  • Importing files from different folder
  • Relative imports for the billionth time
  • How to import a module given the full path?
  • https://docs.python.org/3/reference/import.html (even the official documentation can be helpful at times :)

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

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

是否使用-m选项执行Python代码.

这篇关于如何导入另一个目录中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆