python 导入其他目录下的模块

本文详细解析了Python中如何从不同目录导入模块,包括当前目录、子目录、父目录及任意路径下的模块导入方法。关键在于确保目标模块路径位于sys.path中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

关键:被导入模块所在文件夹的路径需要出现在sys.path中 

python中从其他目录中导入模块的关键是:系统(sys)能够找到通向模块文件的路径,即,sys.path中包含对应模块文件的路径。

python中导入其他目录下的模块,本文主要介绍以下四种情况:

  • 从当前目录下导入模块
  • 从当前目录的子目录中导入模块
  • 从当前目录的父目录导入模块
  • 通用:从任意文件夹路径下导入模块。

1. 从当前目录导入模块

这种情况的程序结构如下:

--base_dir
    |--module1.py
        def func1()
        def func2()
    |--module2.py

要想在module2.py中导入module1.py中的func1,func2函数,直接使用以下命令即可。

# 在module2.py中
from module1 import func1,func2

2. 从当前目录的子目录中导入模块

程序结构如下所示:

--base_dir
    |--son_dir
        ||--module1.py
            def func1()
            def func2()
    |--module2.py

此时,要想在module2.py中导入module1.py中的func1,func2函数,需要在module1.py所在的文件夹son_dir下添加一个__init__.py文件,只有这样,son_dir才会成为一个package,否则不能调用。

此时,程序结构如下:

--base_dir
    |--son_dir
        ||--__init__.py # 新增加的文件,可以为空,使son_dir变成可调用的package
        ||--module1.py
            def func1()
            def func2()
    |--module2.py

然后,就可以在module2.py中以以下形式引入module1.py中的文件。

# 在module2.py中
from son_dir.module1 import func1,func2

3. 从父目录中导入模块

程序结构示意图如下:

--base_dir
    |--module1.py
        def func1()
        def func2()
    |--son_dir
        ||--module2.py
           

我们想在 son_dir.module2.py中导入base_dir.module1.py中的func1,func2函数。

此时我们需要进行如下处理:

# 脚本 mudule2.py 中
import sys
sys.path.append("..") # 将父目录放入系统路径中,不需要再base_dir中增加__init__.py脚本。
# 备注:sys.path.append中的内容也可以是module1.py 所在文件夹的全局路径
from module1 import func1,func2

4. 通用:从任意文件夹路径下导入模块

如以上分析,python中导入某个模块,只需要该模块所在的文件夹路径在sys.path中即可,所以,我们可以用以下通用方式处理模块导入的问题。

程序结构示意图:

--any_dir1 # 任意文件夹位置
    |--mudule1.py 
        def func1()
        def func2()

--any_dir2 # 任意文件夹位置
    |--module2.py 

我们想在module2.py中导入module1中的func1,func2,与情况3相似,我们可以用以下处理:

# 脚本 mudule2.py 中
import sys
sys.path.append("/global/path/to/any_dir1") # 将module1所在的文件夹路径放入sys.path中
from module1 import func1,func2

参考:https://blog.csdn.net/zhang89xiao/article/details/53521366

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值