自定义模块导入的实用方法
00一个大坑
这个问题是我在使用pycharm中的copy path获取当前文件的绝对路径时遇到。
结果获取到的路径如下!!!
E:\text1\day24(模块)\模块导入练习1\当前要执行的文件.py
一开始没有发现错在哪里,直到使用print(__file__)
发现真正的路径是:
E:/text1/day24(模块)/模块导入练习1/当前要执行的文件.py
’\‘ 和 ’/‘ 的差距
01 自定义的模块导入一
# import 模块# 模块.func()# from 模块 import func1# func1()# from 包 import 模块2# 模块2.func2()path='E:/text1/day24(模块)/模块导入练习1/包' # E:/text1/day24(模块)/模块导入练习1/包/模块2.py # E:\text1\day24(模块)\模块导入练习1\包\模块2.py # E:\text1\day24(模块)\模块导入练习1\包import syssys.path.append(path)print(sys.path)import 模块2模块2.func2()print(__file__)
02 自定义的模块导入二
# import sys# sys.path.append('E:/text1/day24(模块)/模块导入练习2/core')# import main# main.func3() # E:/text1/day24(模块)/模块导入练习2/core# print(__file__) # E:/text1/day24(模块)/模块导入练习2/bin/start.py# rep=__file__.split('/')# print(rep)## print(rep[:-2])# base_path='/'.join(rep[:-2])# print(base_path) # E:/text1/day24(模块)/模块导入练习2## import sys# sys.path.append(base_path)# from core import main## main.func3()# 简化rep=__file__.split('/')base_path='/'.join(rep[:-2])import syssys.path.append(base_path)from core import mainmain.func3()
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。