sys.path
模組搜尋路徑的字串列表。由環境變數pythonpath初始化得到。
sys.path[0]是呼叫python直譯器的當前指令碼所在的目錄。
sys.argv
乙個傳給python指令碼的指令引數列表。
sys.argv[0]是指令碼的名字(由系統決定是否是全名)
假設顯示呼叫python指令,如 python demo.py ,會得到絕對路徑;
若直接執行指令碼,如 ./demo.py ,會得到相對路徑。
os.getcwd()
獲取當前工作路徑。在這裡是絕對路徑。
__file__
獲得模組所在的路徑,可能得到相對路徑。
如果顯示執行python,會得到絕對路徑。
若按相對路徑來直接執行指令碼./pyws/path_demo.py
,會得到相對路徑。
為了獲取絕對路徑,可呼叫os.path.abspath()
os.path 中的一些方法
os.path.split(path)
將路徑名稱分成頭和尾一對。尾部永遠不會帶有斜槓。如果輸入的路徑以斜槓結尾,那麼得到的空的尾部。
如果輸入路徑沒有斜槓,那麼頭部位為空。如果輸入路徑為空,那麼得到的頭和尾都是空。
os.path.realpath(path)
返回特定檔名的絕對路徑。
**示例
環境 win7, python2.7
以 /e/pyws/path_demo.py 為例
? 1
2
3
4
5
6
7
8
9
10
11
12
13
#!/usr/bin/env python
import
os
import
sys
if
__name__
=
=
'__main__'
:
print
"sys.path[0] ="
, sys.path[
0
]
print
"sys.argv[0] ="
, sys.argv[
0
]
print
"__file__ ="
, __file__
print
"os.path.abspath(__file__) ="
, os.path.abspath(__file__)
print
"os.path.realpath(__file__) = "
, os.path.realpath(__file__)
print
"os.path.dirname(os.path.realpath(__file__)) ="
, os.path.dirname(os.path.realpath(__file__))
print
"os.path.split(os.path.realpath(__file__)) ="
, os.path.split(os.path.realpath(__file__))
print
"os.getcwd() ="
, os.getcwd()
在 /d 中執行,輸出為
? 1
2
3
4
5
6
7
8
9
$ python
/
e
/
pyws
/
path_demo.py
sys.path[
0
]
=
e:\pyws
sys.argv[
0
]
=
e:
/
pyws
/
path_demo.py
__file__
=
e:
/
pyws
/
path_demo.py
os.path.abspath(__file__)
=
e:\pyws\path_demo.py
os.path.realpath(__file__)
=
e:\pyws\path_demo.py
os.path.dirname(os.path.realpath(__file__))
=
e:\pyws
os.path.split(os.path.realpath(__file__))
=
(
'e:\\pyws'
,
'path_demo.py'
)
os.getcwd()
=
d:\
在e盤中用命令列直接執行指令碼
? 1
2
3
4
5
6
7
8
9
$ .
/
pyws
/
path_demo.py
sys.path[
0
]
=
e:\pyws
sys.argv[
0
]
=
.
/
pyws
/
path_demo.py
__file__
=
.
/
pyws
/
path_demo.py
os.path.abspath(__file__)
=
e:\pyws\path_demo.py
os.path.realpath(__file__)
=
e:\pyws\path_demo.py
os.path.dirname(os.path.realpath(__file__))
=
e:\pyws
os.path.split(os.path.realpath(__file__))
=
(
'e:\\pyws'
,
'path_demo.py'
)
os.getcwd()
=
e:\
獲取 sh 檔案當前所在目錄
cd dirname 0 echo basename 0 is in pwd cd 說明 0當前shell程式的檔名 dirname 0,獲取當前shell程式的路徑 cd dirname 0 進入當前shell程式的目錄 dirname 從檔名剝離非目錄的字尾,列印去除了 後面部分的name 如果...
Python 獲取當前檔案所在目錄
python下獲取檔案所在的絕對目錄,大都通過 os.path.abspath,但如果你在其他目錄下,通過絕對路徑獲取,這時就會有錯。例如 步驟 在當用目錄執行 import os import sys print os.path.abspath main.py 結果為 home abc tiran...
獲取當前所在星期的星期一
1 使用jdk獲取當前所在星期的星期一 取本週7天的第一天 周一的日期 public static date getnowweekbegin else gregoriancalendar currentdate new gregoriancalendar currentdate.add gregor...