os.path.dirname(__file__)方法詳解


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

1.  import os  
2.  #該文件所在位置:D:\第1層\第2層\第3層\第4層\第5層\test11.py  

4.  path1 = os.path.dirname(__file__)  
5.  print(path1)#獲取當前運行腳本的絕對路徑  

7.  path2 = os.path.dirname(os.path.dirname(__file__)) #  
8.  print(path2)#獲取當前運行腳本的絕對路徑(去掉最后一個路徑)  

10.  path3 = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))  
11.  print(path3)#獲取當前運行腳本的絕對路徑(去掉最后2個路徑)  

13.  path4 = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))  
14.  print(path4)#獲取當前運行腳本的絕對路徑(去掉最后3個路徑)  

16.  path5 = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))))  
17.  print(path5)#獲取當前運行腳本的絕對路徑(去掉最后4個路徑)  

19.  path6 = os.__file__                  #獲取os所在的目錄  
20.  print(path6)  

結果:

1.  C:\Python352\python.exe D:/第1層/第2層/第3層/第4層/第5層/test11.py  
2.  D:/第1層/第2層/第3層/第4層/第5層  
3.  D:/第1層/第2層/第3層/第4層  
4.  D:/第1層/第2層/第3層  
5.  D:/第1層/第2層  
6.  D:/第1層  
7.  C:\Python352\lib\os.py  
8.
9.  Process finished with exit code 0

os.path.dirname(file)返回腳本的路徑,但是需要注意一下幾點:

  • 必須是實際存在的.py文件,如果在命令行執行,則會引發異常NameError: name 'file' is not defined;
  • 在運行的時候如果輸入完整的執行的路徑,則返回.py文件的全路徑如:Python c:/test/test.py 則返回路徑 c:/test,如果是python test.py 則返回空;
  • 結合os.path.abspath用,效果會好,如果大家看過一些python架構的代碼的話,會發現經常有這樣的組合:os.path.dirname(os.path.abspath(file)),os.path.abspath(file)返回的是.py文件的絕對路徑。

這就是os.path.dirname(file)的用法,其主要總結起來有:

  • 不要在命令行的形式來進行os.path.dirname(file)這種形式來使用這個函數;
  • 結合os.path.abspath()使用

 

 

 

 

 

 

 

 

 

 

 

1.  import os  
2.  #該文件所在位置:D:\第1層\第2層\第3層\第4層\第5層\test11.py 

4.  path1 = os.path.dirname(__file__)  
5.  print(path1)#獲取當前運行腳本的絕對路徑 

7.  path2 = os.path.dirname(os.path.dirname(__file__)) # 
8.  print(path2)#獲取當前運行腳本的絕對路徑(去掉最后一個路徑) 

10.  path3 = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))  
11.  print(path3)#獲取當前運行腳本的絕對路徑(去掉最后2個路徑) 

13.  path4 = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))  
14.  print(path4)#獲取當前運行腳本的絕對路徑(去掉最后3個路徑) 

16.  path5 = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))))  
17.  print(path5)#獲取當前運行腳本的絕對路徑(去掉最后4個路徑) 

19.  path6 = os.__file__                  #獲取os所在的目錄 
20.  print(path6)  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM