Python獲取當(dāng)前路徑實(shí)現(xiàn)代碼
import os,sys
使用sys.path[0]、sys.argv[0]、os.getcwd()、os.path.abspath(__file__)、os.path.realpath(__file__)
sys.path是Python會(huì)去尋找模塊的搜索路徑列表,sys.path[0]和sys.argv[0]是一回事因?yàn)镻ython會(huì)自動(dòng)把sys.argv[0]加入
sys.path。
如果你在C:/test目錄下執(zhí)行python getpath/getpath.py,那么os.getcwd()會(huì)輸出“C:/test”,sys.path[0]會(huì)輸出“C:/test/getpath”。
如果你用py2exe模塊把Python腳本編譯為可執(zhí)行文件,那么sys.path[0]的輸出還會(huì)變化:
如果把依賴庫(kù)用默認(rèn)的方式打包為zip文件,那么sys.path[0]會(huì)輸出“C:/test/getpath/libarary.zip”;
如果在setup.py里面指定zipfile=None參數(shù),依賴庫(kù)就會(huì)被打包到exe文件里面,那么sys.path[0]會(huì)輸出“C:/test/getpath/getpath.exe”。
#!/bin/env python#-*- encoding=utf8 -*-import os,sysif __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]
輸出結(jié)果:
D:/>python ./python_test/test_path.py__file__=./python_test/test_path.pyos.path.realpath(__file__)=D:/python_test/test_path.pyos.path.dirname(os.path.realpath(__file__))=D:/python_testos.path.split(os.path.realpath(__file__))=D:/python_testos.path.abspath(__file__)=D:/python_test/test_path.pyos.getcwd()=D:/sys.path[0]=D:/python_testsys.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的所在目錄
正確獲取當(dāng)前的路徑:
__file__是當(dāng)前執(zhí)行的文件 # 獲取當(dāng)前文件__file__的路徑 print "os.path.realpath(__file__)=%s" % os.path.realpath(__file__) # 獲取當(dāng)前文件__file__的所在目錄 print "os.path.dirname(os.path.realpath(__file__))=%s" % os.path.dirname(os.path.realpath(__file__)) # 獲取當(dāng)前文件__file__的所在目錄 print "os.path.split(os.path.realpath(__file__))=%s" % os.path.split(os.path.realpath(__file__))[0]
感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
新聞熱點(diǎn)
疑難解答
圖片精選