本文实例讲述了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__的区别是这样的:
假设目录结构是:
总之,举例来讲,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的所在目录