在为自己的crifanLib的python写demo
尝试去导入父级目录中的crifanFile
然后试了试:..
from ..crifanFile import getFileFolderSize, formatSize
好像可以支持:
![](https://www.crifan.com/files/pic/uploads/2021/03/6ffc3b82b23d4854bb96ec4f77e7db88.jpg)
但是运行失败:
发生异常: ValueError attempted relative import beyond top-level package File "/Users/crifan/dev/dev_root/crifan/CrifanLib/crifanLib/python/crifanLib/demo/crifanFileDemo.1.py", line 1, in <module> from ..crifanFile import getFileFolderSize, formatSize
![](https://www.crifan.com/files/pic/uploads/2021/03/5b785eba721849959791c1e2889b8632.jpg)
所以去搜:
python import parent directory
和:
去试试:…
![](https://www.crifan.com/files/pic/uploads/2021/03/9ba65da54da1481ebf12d5b9bb3d8738.jpg)
![](https://www.crifan.com/files/pic/uploads/2021/03/7ed3933e2a414c9998a7002a4d17de1b.jpg)
from ...crifanLib import crifanFile
结果:
问题依旧:
![](https://www.crifan.com/files/pic/uploads/2021/03/5e8799a8ee6c416abd4091f66066bbf0.jpg)
from ... import crifanFile
结果:问题依旧。
看到别人提示了:
“Relative imports (as in from .. import mymodule) only work in a package. ”
python – Import file from parent directory? – Stack Overflow
用:
import sys import os curFolder = os.path.abspath(__file__) parentFolder = os.path.dirname(curFolder) parentParentFolder = os.path.dirname(parentFolder) parentParentParentFolder = os.path.dirname(parentParentFolder) sys.path.append(curFolder) sys.path.append(parentFolder) sys.path.append(parentParentFolder) sys.path.append(parentParentParentFolder) from crifanFile import getFileFolderSize, formatSize
是可以的:
![](https://www.crifan.com/files/pic/uploads/2021/03/9bad785e628f406fabd0102d46866a8b.jpg)
看到google的动态提示:
![](https://www.crifan.com/files/pic/uploads/2021/03/fe57558c7fec40d290bbffc5f3fe5707.jpg)
所以再去搜:
python 3 import from parent directory
【总结】
在:
/Users/crifan/dev/dev_root/crifan/CrifanLib/crifanLib/python/crifanLib/demo/crifanFileDemo.1.py
最后用:
import sys import os curFolder = os.path.abspath(__file__) parentFolder = os.path.dirname(curFolder) parentParentFolder = os.path.dirname(parentFolder) parentParentParentFolder = os.path.dirname(parentParentFolder) sys.path.append(curFolder) sys.path.append(parentFolder) sys.path.append(parentParentFolder) sys.path.append(parentParentParentFolder) from crifanFile import getFileFolderSize, formatSize
可以导入:
/Users/crifan/dev/dev_root/crifan/CrifanLib/crifanLib/python/crifanLib
下面的:
/Users/crifan/dev/dev_root/crifan/CrifanLib/crifanLib/python/crifanLib/crifanFile.py
然后就可以继续测试了。
注:
实际情况中,一般只需要parentFolder就够了
此处之所以继续导入parentParentFolder、parentParentParentFolder是因为此处的crifanFile内容导入了别的库,其所在路径是父级的父级,父级的父级的父级 的路径。
转载请注明:在路上 » 【已解决】Python导入父级目录中的模块