如何导入另一个目录中的文件? [英] How do I import a file that is in another directory?
本文介绍了如何导入另一个目录中的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
-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):
- Python模块之间有什么区别和一个Python包?
- 什么是__init__.py?
- 从其他文件夹导入文件
- 十亿分之一的相对进口量
- 如何在给定完整路径的情况下导入模块? /a>
- https://docs.python.org/3/reference/import.html (有时甚至是官方文档也可能有帮助:)
- 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
这篇关于如何导入另一个目录中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文