--- url: https://blog.csdn.net/lipengfei0427/article/details/109411917 fid: 20240710-095947 title: python中跨目录(文件)import函数_python 从一个子目录导入另一个子目录的函数-CSDN博客 tags: import, module --- (python-import-module-across-folders)= # python中跨目录(文件)import函数 From: [python中跨目录(文件)import函数_python 从一个子目录导入另一个子目录的函数](https://blog.csdn.net/lipengfei0427/article/details/109411917) 原文转载 ## 同级目录下的调用 文件层次结构 ```python --src   |--test1.py   |--test2.py ``` 若在程序test2.py中导入模块test1, 则直接使用 ```python import test1 test1.fun1() # 或 from test1 import * ``` 也可以直接导入指定函数 ```python from test1 import fun1 fun1() # 注意此时可以直接以函数名加括号的方式调用 ``` ## 调用子目录下面的模块 文件层次结构 ```python --src   |--top.py   |--lib   |  |--mod1.py ``` 这时看到top.py和lib目录(即mod1.py的父级目录)在同一层级,如果想在程序top.py中导入模块mod1.py ,可以在lib件夹中建立空文件__init__.py文件(也可以在该文件中自定义输出模块接口),然后使用: ```python # 从lib文件夹中引用mod1 from lib import mod1 # 使用函数 mod1.fun() ``` 加入__init__.py后的文件层次结构 ```python --src   |--top.py   |--lib   |  |--mod1.py   |  |--__init__.py ``` ## 跨目录调用文件下面的模块 文件层次结构 ```python --src   |--test1.py --des   |--test2.py ``` 若在test2.py中导入test1.py的模块,需要(在 sys path 环境变量中)增加调用文件的目录,可以是相对路径也可以是绝对路径。 导入sys模块,然后在sys的path下添加路径,再导入test1.py。 ```python import sys # 导入sys模块 sys.path.append("..") from src import test1 ``` 上面的方法临时使用没有问题,但如果在 des 中有大量的测试文件,都这样写会比较繁琐,并且可维性不好。建议在操作系统中设置 PYTHONPATH 环境变量解决。 ## 参考链接 [https://blog.csdn.net/winycg/article/details/78512300](https_blog.csdn.net_winycg_article_details_78512300) [https://www.jb51.net/article/181540.htm](https_www.jb51.net_article_181540.htm)