os.path.abspath(__file__)與os.path.dirname()以及os.path.basename(__file__)的用法詳解

1、os.path.abspath(_file_)

  • os.path.dirname(_file_) 返回腳本的絕對路徑
  • 不可以直接在命令行運行該文件, 否則會報錯 “NameError: name '__file__' is not defined”
  • 可直接運行該文件或者調用該文件也可以
1.1、在 D:\xxxx\xx\util 路徑下建立test.py文件如下:
import os
# 返回腳本絕對路徑
print(os.path.abspath(__file__))
1.2、在cmd中運行該文件,得結果如下:

在這裏插入圖片描述

2、os.path.dirname()

  • os.path.dirname(path) 返回path的父路徑
  • 可嵌套使用,如 os.path.dirname(os.path.dirname(path) ) 返回父路徑的父路徑
  • 可以 os.path.abspath(_file_) 聯合使用
2.1、在 D:\xxxx\xx\util 路徑下建立test.py文件如下:
import os
# 返回腳本絕對路徑
print(os.path.abspath(__file__))
# 返回腳本上兩層目錄路徑
root_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
print(root_path)
2.2、在cmd中運行該文件,得結果如下:

在這裏插入圖片描述

3、os.path.basename(_file_)

  • os.path.basename(_file_) 返回腳本的文件名稱
  • 不可以直接在命令行運行該文件, 否則會報錯 “NameError: name '__file__' is not defined”
  • 可直接運行該文件或者調用該文件也可以
3.1、在 D:\xxxx\xx\util 路徑下建立test.py文件如下:
import os
# 返回腳本的文件名稱
print(os.path.basename(__file__))
3.2、在cmd中運行該文件,得結果如下:

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章