Python 獲取當前所在目錄的方法詳解
sys.path
模塊搜索路徑的字符串列表。由環(huán)境變量PYTHONPATH初始化得到。
sys.path[0]是調(diào)用Python解釋器的當前腳本所在的目錄。
sys.argv
一個傳給Python腳本的指令參數(shù)列表。
sys.argv[0]是腳本的名字(由系統(tǒng)決定是否是全名)
假設(shè)顯示調(diào)用python指令,如 python demo.py ,會得到絕對路徑;
若直接執(zhí)行腳本,如 ./demo.py ,會得到相對路徑。
os.getcwd()
獲取當前工作路徑。在這里是絕對路徑。
https://docs.python.org/2/library/os.html#os.getcwd
__file__
獲得模塊所在的路徑,可能得到相對路徑。
如果顯示執(zhí)行Python,會得到絕對路徑。
若按相對路徑來直接執(zhí)行腳本 ./pyws/path_demo.py
,會得到相對路徑。
為了獲取絕對路徑,可調(diào)用 os.path.abspath()
os.path 中的一些方法
os.path.split(path)
將路徑名稱分成頭和尾一對。尾部永遠不會帶有斜杠。如果輸入的路徑以斜杠結(jié)尾,那么得到的空的尾部。
如果輸入路徑?jīng)]有斜杠,那么頭部位為空。如果輸入路徑為空,那么得到的頭和尾都是空。
https://docs.python.org/2/library/os.path.html#os.path.split
os.path.realpath(path)
返回特定文件名的絕對路徑。
https://docs.python.org/2/library/os.path.html#os.path.realpath
代碼示例
環(huán)境 Win7, Python2.7
以 /e/pyws/path_demo.py 為例
#!/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 中運行,輸出為
$ 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盤中用命令行直接執(zhí)行腳本
$ ./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:\
相關(guān)文章
python使用nibabel和sitk讀取保存nii.gz文件實例
這篇文章主要介紹了python使用nibabel和sitk讀取保存nii.gz文件實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07淺談Python中文件夾和python package包的區(qū)別
這篇文章主要介紹了淺談Python中文件夾和python package包的區(qū)別,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06Django框架中數(shù)據(jù)的連鎖查詢和限制返回數(shù)據(jù)的方法
這篇文章主要介紹了Django框架中數(shù)據(jù)的連鎖查詢和限制返回數(shù)據(jù)的方法,Django是Python重多高人氣框架中最為著名的一個,需要的朋友可以參考下2015-07-07詳解使用python的logging模塊在stdout輸出的兩種方法
這篇文章主要介紹了詳解使用python的logging模塊在stdout輸出的相關(guān)資料,需要的朋友可以參考下2017-05-05