飘逸的python - import上一级目录的模块
python中,import module会去sys.path搜索,sys.path是个列表,并且我们可以动态修改。
要import某个目录的module,我们sys.path.insert(0,somedir)来加入搜索路径,就可以import了。
既然这样,要import上一级目录的module,可以sys.path.insert(0,parentdir)。
不过这种写绝对路径的方式,如果文件放到其它地方,就不行了。
所以用动态方法来获取上一级目录。
import os,sysparentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))sys.path.insert(0,parentdir)