码迷,mamicode.com
首页 > 其他好文 > 详细

import上一级目录的模块(转)

时间:2014-06-18 09:37:57      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:style   class   http   tar   ext   com   

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

import os,sys
parentdir = 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)可以确保先搜索这个路径。

import上一级目录的模块(转),布布扣,bubuko.com

import上一级目录的模块(转)

标签:style   class   http   tar   ext   com   

原文地址:http://www.cnblogs.com/zhangjunjun203/p/3793286.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!