首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > perl python >

飘逸的python - import上一级索引的模块

2013-09-21 
飘逸的python - import上一级目录的模块python中,import module会去sys.path搜索,sys.path是个列表,并且我

飘逸的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) 

为什么用sys.path.insert(0,parentdir) 而不是用sys.path.append(parentdir)呢
因为是遍历搜索路径的,所以如果在其它路径里也有个同名的module,会import错。用sys.path.insert(0,parentdir)可以确保先搜索这个路径。

热点排行