python2.7获取当前脚本目录

本文实例讲述了Python获取运行目录与当前脚本目录的方法。分享给大家供大家参考。具体实现方法如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
import os
import sys
#运行目录
CurrentPath = os.getcwd()
print CurrentPath
#当前脚本目录
print "##################################################"
print os.path
print sys.argv[ 0 ]
print os.path.split( os.path.realpath( sys.argv[ 0 ] ) )
print "##################################################"
ScriptPath = os.path.split( os.path.realpath( __file__ ) )[ 0 ]
print ScriptPath

运行结果如下:

?
1
2
3
4
5
6
7
C:\pythondemo
##################################################
<module 'ntpath' from 'C:\Python27\lib\ntpath.pyc' >
C: / pythondemo / 1.py
( 'C:\\pythondemo' , '1.py' )
##################################################
C:\pythondemo
实例说明

总之,举例来讲,os.getcwd()、sys.path[0] (sys.argv[0])和__file__的区别是这样的:
假设目录结构是:
复制代码 代码如下:

C:test

  [dir] getpath

    [file] path.py
    [dir] sub

      [file] sub_path.py


然后我们在C:\test下面执行python getpath/path.py,这时sub_path.py里面与各种用法对应的值其实是:
os.getcwd() “C:\test”,取的是起始执行目录
sys.path[0]或sys.argv[0] “C:\test\getpath”,取的是被初始执行的脚本的所在目录
os.path.split(os.path.realpath(__file__))[0] “C:\test\getpath\sub”,取的是__file__所在文件sub_path.py的所在目录
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值