Chinaunix首页 | 论坛 | 博客
  • 博客访问: 471252
  • 博文数量: 135
  • 博客积分: 1860
  • 博客等级: 上尉
  • 技术积分: 1441
  • 用 户 组: 普通用户
  • 注册时间: 2008-01-05 20:39
文章分类
文章存档

2012年(2)

2011年(130)

2009年(2)

2008年(1)

我的朋友

分类: Python/Ruby

2011-08-11 16:40:05

 

python __file__ 与相对路径

2011年7月18日

18:08

python __file__ 与相对路径

2008-06-29 12:03:01|  分类: python |  标签: |字号大中小 订阅

__file__ 来获得脚本所在的路径是比较方便的,但这可能得到的是一个相对路径,比如在脚本test.py中写入:

#!/usr/bin/env python

print __file__

按相对路径./test.py来执行,则打印得到的是相对路径,

按绝对路径执行则得到的是绝对路径。

而按用户目录来执行(~/practice/test.py),则得到的也是绝对路径(~被展开)

所以为了得到绝对路径,我们需要 os.path.realpath(__file__)

 

获取绝对路径的目录路径:os.path.dirname(os.path.realpath(__file__))

获取脚本名称:os.path.basename(os.path.realpath(__file__)) or os.path.basename(__file__)

 

Pasted from <http://taoyh163.blog.163.com/blog/static/195803562008529031652/>

 

阅读(986) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~