Python跨文件夹导入模块:如何从其他文件夹导入指定模块?
Python跨文件夹导入问题解决方案
项目结构确认
d:\ └── project Main ├── First Folder │ └── my_main_file.py └── Second Folder └── my_second_file.py
注意事项
建议将带空格的文件夹名修改为无空格格式(比如First_Folder),避免导入时出现语法问题。
方法1:动态添加项目根目录到Python路径
在my_second_file.py开头添加以下代码,手动将项目根目录加入Python的搜索路径,从而可以直接导入目标模块:
import sys import os # 获取项目根目录(project Main的绝对路径) project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) # 将根目录加入Python搜索路径 sys.path.append(project_root) # 按需导入:类、全局变量等 from First_Folder.my_main_file import Database_connection, passkey_general, db_name_general # 使用示例 # 实例化类并调用实例方法 db_instance = Database_connection() db_instance.establish_connection_general() # 直接使用全局变量 print(passkey_general)
方法2:将文件夹标记为Python包
- 在
First Folder和Second Folder中分别新建空的__init__.py文件,将这两个文件夹标记为Python可识别的包。 - 同样在
my_second_file.py中添加路径配置并导入:
import sys import os project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) sys.path.append(project_root) from First_Folder.my_main_file import Database_connection # 调用类方法(需先实例化) conn = Database_connection() conn.establish_connection_general()
方法3:设置系统环境变量(永久生效)
通过设置PYTHONPATH环境变量,让Python启动时自动识别项目根目录,无需每次在代码中添加路径:
- Windows系统:右键「此电脑」→ 属性 → 高级系统设置 → 环境变量 → 系统变量 → 新建
- 变量名:
PYTHONPATH - 变量值:
d:\project Main
- 变量名:
- 重启终端或IDE后生效,之后在
my_second_file.py中可直接导入:
from First_Folder.my_main_file import Database_connection # 实例化并调用方法 db_conn = Database_connection() db_conn.establish_connection_general()
关于establish_connection_general方法的导入说明
establish_connection_general是Database_connection类的实例方法,无法单独直接导入。如果想无需实例化直接调用,可以将其修改为类方法或静态方法:
修改my_main_file.py中的方法定义
class Database_connection(QWidget): # 改为类方法 @classmethod def establish_connection_general(cls): try: connection_general = sqleet.connect(db_name_general, key=passkey_general) print("open successfully") return connection_general except Exception as e: if show_errormsg == "show": # 同时需将handle_error也改为类方法 cls.handle_error(e) else: pass @classmethod def handle_error(cls, error): # 原代码中的self替换为cls,其他逻辑保持不变 exc_type, exc_value, exc_traceback = sys.exc_info() filenamewithpath = exc_traceback.tb_frame.f_code.co_filename head,tail = os.path.split((filenamewithpath)) lineno = exc_traceback.tb_lineno name = exc_traceback.tb_frame.f_code.co_name type = exc_type.__name__ nl = '\n' kk = f'File Name : {tail[:-3]}{nl}'\ f'Line No. : {lineno}{nl}'\ f'Type : {type}{nl}'\ f'Name : {name}{nl}' # 注意:QMessageBox需要QApplication实例,若在类方法中直接调用可能需确保App已初始化 msg = QMessageBox() msg.setFixedSize(1600,400) msg.setWindowTitle(" Error/Bugs Information") msg.setWindowIcon(QIcon('icon\close006.png')) fd = " " msg.setText(f'{type} - {lineno}{fd}') msg.setIcon(QMessageBox.Information) msg.setStandardButtons(QMessageBox.Ok) msg.setDefaultButton(QMessageBox.Ok) msg.setInformativeText("") msg.setDetailedText(kk) msg.show()
修改后直接调用
from First_Folder.my_main_file import Database_connection # 无需实例化,直接调用类方法 Database_connection.establish_connection_general()
内容的提问来源于stack exchange,提问作者tckraomuqnt
相关产品推荐
相关产品推荐

