日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

os.path.dirname( __ file __ ) 2018/6/2

發布時間:2025/3/21 编程问答 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 os.path.dirname( __ file __ ) 2018/6/2 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

os.path.dirname( __ file __ ) 2018/6/2

該測試腳本所在的位置:D:\第1層\第2層\第3層\第4層\第5層\test11.py

import os #該文件所在位置:D:\第1層\第2層\第3層\第4層\第5層\test11.pypath1 = os.path.dirname(__file__) print(path1)#獲取當前運行腳本的絕對路徑path2 = os.path.dirname(os.path.dirname(__file__)) # print(path2)#獲取當前運行腳本的絕對路徑(去掉最后一個路徑)path3 = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) print(path3)#獲取當前運行腳本的絕對路徑(去掉最后2個路徑)path4 = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) print(path4)#獲取當前運行腳本的絕對路徑(去掉最后3個路徑)path5 = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))) print(path5)#獲取當前運行腳本的絕對路徑(去掉最后4個路徑)path6 = os.__file__ #獲取os所在的目錄 print(path6)

運行的結果:

C:\Python352\python.exe D:/第1層/第2層/第3層/第4層/第5層/test11.py D:/第1層/第2層/第3層/第4層/第5層 D:/第1層/第2層/第3層/第4層 D:/第1層/第2層/第3層 D:/第1層/第2層 D:/第1層 C:\Python352\lib\os.pyProcess finished with exit code 0
  • 解釋:
  • os.path.dirname( __ file__ )返回腳本的路徑,但是需要注意一下幾點:

1、必須是實際存在的.py文件,如果在命令行執行,則會引發異常NameError: name '__ file__' is not defined

2、在運行的時候如果輸入完整的執行的路徑,則返回.py文件的全路徑如:

python c:/test/test.py 則返回路徑 c:/test ,如果是python test.py 則返回空

3、結合os.path.abspath用,效果會好,如果大家看過一些python架構的代碼的話,會發現經常有這樣的組合

os.path.dirname(os.path.abspath(__ file__ )), 其中os.path.abspath(__ file__)返回的是.py文件的絕對路徑

這就是os.path.dirname(__ file__)的用法,其主要總結起來有:
1、不要已命令行的形式來進行os.path.dirname( file)這種形式來使用這個函數

2、結合os.path.abspath()使用

轉載于:https://www.cnblogs.com/GGGGGGZX/p/9124183.html

《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀

總結

以上是生活随笔為你收集整理的os.path.dirname( __ file __ ) 2018/6/2的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。