Python 獲取路徑的方法

2021-09-10 03:32:44 字數 2295 閱讀 8148

os.getcwd(

)# 獲取當前執行python命令所在絕對路徑,類似pwd

os.path.abspath(os.path.dirname(__file__)

)# 獲取要執行的python檔案所在的絕對路徑。

os.path.dirname(__file__)

# 獲取python檔案所在的上級目錄的相對路徑。__file__ 是python檔案所在的相對路徑,包含python檔名。

os.path.realpath(

)# 獲取有執行的pyton檔案所在的絕對路徑,是真實檔案路徑,而軟連線路徑,這也是和os.path.abspath的主要區別。

測試

import os

print

(os.getcwd())

print

(os.path.dirname(__file__)

)print

(os.path.abspath(os.path.dirname(__file__)))

print

(os.path.realpath(os.path.dirname(__file__)))

print

(__file__)

print

(os.path.abspath(__file__)

)print

(os.path.realpath(__file__)

)

在檔案所在目錄執行python檔案輸出:

liangkai@liangkaidemac-mini [14:16:48]

[~/desktop/python/practice]

[master *]

-> % python getpath.py

/users/liangkai/desktop/python/practice

# 在當前檔案所在目錄執行,os.path.dirname(__file__)為空

/users/liangkai/desktop/python/practice # 檔案所在上級目錄的絕對路徑

/users/liangkai/desktop/python/practice # 檔案所在上級目錄的絕對路徑

getpath.py # __file__可以直接輸出檔案的相對路徑

/users/liangkai/desktop/python/practice/getpath.py

/users/liangkai/desktop/python/practice/getpath.py

liangkai@liangkaidemac-mini [14:16:52]

[~/desktop/python]

[master *]

-> % python practice/getpath.py

/users/liangkai/desktop/python

practice

/users/liangkai/desktop/python/practice

/users/liangkai/desktop/python/practice

practice/getpath.py

/users/liangkai/desktop/python/practice/getpath.py

/users/liangkai/desktop/python/practice/getpath.py

在檔案所在目錄的上兩級目錄執行python檔案,輸出:

liangkai@liangkaidemac-mini [14:17:14]

[~/desktop]

-> % python python/practice/getpath.py

/users/liangkai/desktop

python/practice

/users/liangkai/desktop/python/practice

/users/liangkai/desktop/python/practice

python/practice/getpath.py

/users/liangkai/desktop/python/practice/getpath.py

/users/liangkai/desktop/python/practice/getpath.py

小結:

python 獲取路徑方法

coding utf8 import os realpath 獲得的是該方法所在的指令碼的路徑 def getpath realpath 獲取當前檔案位置 file os.path.realpath file print file file 獲取當前執行指令碼的絕對路徑。filepath os.pa...

Python 獲取當前路徑的方法

python2.7 中獲取路徑的各種方法 sys.path 模組搜尋路徑的字串列表。由環境變數pythonpath初始化得到。sys.path 0 是呼叫python直譯器的當前指令碼所在的目錄。sys.ar 乙個傳給python指令碼的指令引數列表。sys.ar 0 是指令碼的名字 由系統決定是否...

獲取路徑的方法

c 獲取程式路徑的主要方法和區別如下 1.獲取模組的完整路徑 即程式名 vshost.exe 是visual studio宿主應用程式,vs執行除錯時是開啟的其實是這個檔案,這個程式可以讓vs跟蹤除錯資訊。string path1 system.diagnostics.process.getcurr...