自定义模块导入的实用方法

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 sys
sys.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 sys
sys.path.append(base_path)

from core import main

main.func3()

猜你喜欢

转载自blog.51cto.com/13747953/2306656