相对路径与绝对路径

相对路径是相对于当前路径而言的,而绝对路径是相对于根目录而言的。

/ 表示根目录
./ 表示当前路径
../ 表示上一级路径
../../ 表示上两级路径

vscode中python自定义包的模块如何导入其他子包模块

https://yxchangingself.xyz/posts/python-the-module-of-parentpkg-import-the-module-of-childpkg/

解决方法:

  1. 在当前目录下创建一个__init__.py文件
  2. 将子包路径添加到系统路径中
1
2
3
4
5
6
# parent.__init__.py
import sys
import os
sys.path.append(os.path.dirname(os.path.realpath(__file__)))

print('导入了parent包')

python找包会在当前路径和sys.path中去查找,所以可以在导入parent包的时候,将它的路径加入sys.path当中,这样就可以找到parent包的子包了。

同时,因为是在__init__.py中加的,包内文件就不必每次都将粘贴一次这部分代码。

其中,os.path.realpath(file)获取本文件即parent.init.py的真实路径,os.path.dirname()将完整路径中的目录名提取出来,去掉其中的文件名。