?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,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]
輸出結(jié)果:
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的所在目錄?
正確獲取當(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ì)本站的支持!
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺(jué)我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
