html tool

2015年3月25日星期三

python动态导入文件所在的父目录

add:http://blog.csdn.net/handsomekang/article/details/11799281

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

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

没有评论:

发表评论