Python獲取當前路徑實現(xiàn)代碼
Python獲取當前路徑實現(xiàn)代碼
import os,sys
使用sys.path[0]、sys.argv[0]、os.getcwd()、os.path.abspath(__file__)、os.path.realpath(__file__)
sys.path是Python會去尋找模塊的搜索路徑列表,sys.path[0]和sys.argv[0]是一回事因為Python會自動把sys.argv[0]加入
sys.path。
如果你在C:\test目錄下執(zhí)行python getpath\getpath.py,那么os.getcwd()會輸出“C:\test”,sys.path[0]會輸出“C:\test\getpath”。
如果你用py2exe模塊把Python腳本編譯為可執(zhí)行文件,那么sys.path[0]的輸出還會變化:
如果把依賴庫用默認的方式打包為zip文件,那么sys.path[0]會輸出“C:\test\getpath\libarary.zip”;
如果在setup.py里面指定zipfile=None參數(shù),依賴庫就會被打包到exe文件里面,那么sys.path[0]會輸出“C:\test\getpath\getpath.exe”。
#!/bin/env python #-*- encoding=utf8 -*- import os,sys if __name__=="__main__": print "__file__=%s" % __file__ print "os.path.realpath(__file__)=%s" % os.path.realpath(__file__) print "os.path.dirname(os.path.realpath(__file__))=%s" % os.path.dirname(os.path.realpath(__file__)) print "os.path.split(os.path.realpath(__file__))=%s" % os.path.split(os.path.realpath(__file__))[0] print "os.path.abspath(__file__)=%s" % os.path.abspath(__file__) print "os.getcwd()=%s" % os.getcwd() print "sys.path[0]=%s" % sys.path[0] print "sys.argv[0]=%s" % sys.argv[0]
輸出結果:
D:\>python ./python_test/test_path.py __file__=./python_test/test_path.py os.path.realpath(__file__)=D:\python_test\test_path.py os.path.dirname(os.path.realpath(__file__))=D:\python_test os.path.split(os.path.realpath(__file__))=D:\python_test os.path.abspath(__file__)=D:\python_test\test_path.py os.getcwd()=D:\ sys.path[0]=D:\python_test sys.argv[0]=./python_test/test_path.py
os.getcwd() “D:\”,取的是起始執(zhí)行目錄
sys.path[0]或sys.argv[0] “D:\python_test”,取的是被初始執(zhí)行的腳本的所在目錄
os.path.split(os.path.realpath(__file__))[0] “D:\python_test”,取的是__file__所在文件test_path.py的所在目錄
正確獲取當前的路徑:
__file__是當前執(zhí)行的文件 # 獲取當前文件__file__的路徑 print "os.path.realpath(__file__)=%s" % os.path.realpath(__file__) # 獲取當前文件__file__的所在目錄 print "os.path.dirname(os.path.realpath(__file__))=%s" % os.path.dirname(os.path.realpath(__file__)) # 獲取當前文件__file__的所在目錄 print "os.path.split(os.path.realpath(__file__))=%s" % os.path.split(os.path.realpath(__file__))[0]
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關文章
Python編寫的com組件發(fā)生R6034錯誤的原因與解決辦法
pythoncom27.dll可能沒有包含manifest信息,或者沒有包含正確的manifest信息,或者系統(tǒng)中的c++ runtime library受到破壞都有可能造成這種現(xiàn)象2013-04-04python實現(xiàn)dnspod自動更新dns解析的方法
這篇文章主要介紹了python實現(xiàn)的dnspod自動更新dns解析的方法,需要的朋友可以參考下2014-02-02Matplotlib scatter繪制散點圖的方法實現(xiàn)
這篇文章主要介紹了Matplotlib scatter繪制散點圖的方法實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-01-01Python?NLP開發(fā)之實現(xiàn)聊天機器人
這篇文章主要為大家介紹了Python如何實現(xiàn)聊天機器人,即使用自然語言處理?(NLP)?來幫助用戶通過文本、圖形或語音與?Web?服務或應用進行交互,感興趣的可以了解一下2023-05-05Python變量、數(shù)據(jù)類型、數(shù)據(jù)類型轉換相關函數(shù)用法實例詳解
這篇文章主要介紹了Python變量、數(shù)據(jù)類型、數(shù)據(jù)類型轉換相關函數(shù)用法,結合實例形式詳細分析了Python變量類型、基本用法、變量類型轉換相關函數(shù)與使用技巧,需要的朋友可以參考下2020-01-01