python中os.path.join()、os.path.dirname()、os.path.absname()函式的用法
阿新 • • 發佈:2020-10-13
一、os.path.dirname()獲取當前檔案路徑,去掉檔名
目錄結構
我的目錄結構:
os.path.dirname(path)
語法:os.path.dirname(path)
功能:去掉檔名,返回目錄
如:
print(os.path.dirname("E:/Read_File/read_yaml.py")) #結果: E:/Read_File print(os.path.dirname("E:/Read_File")) #結果: E:/
os.path.dirname(__file__)
先了解一下__file__
print(__file__) #結果 E:/Read_File/read_yaml.py
可以看出__file__表示了當前檔案的path
那麼就可以瞭解到os.path.dirname((__file__)和os.path.dirname(“E:/Read_File/read_yaml.py”)是一個意思
再根據os.path.dirname(path)的用法,得出os.path.dirname((__file__)就是得到當前檔案的絕對路徑
print(os.path.dirname(__file__)) #結果: E:/Read_File
擴充套件
若print os.path.dirname(file)所在指令碼是以絕對路徑執行的,則會輸出該指令碼所在的絕對路徑,若以相對路徑執行,輸出空目錄
print(os.path.dirname(__file__))
結果:
二、os.path.absname()函式返回的是包含檔案的絕對路徑
import os ##獲取當前指令碼的路徑 os.path.abspath(__file__) 執行結果:E:\2020_keyword_frame\Conf\ProjVar.py #獲取當前檔案的上一層目錄 os.path.dirname(os.path.abspath(__file__)) 執行結果:E:\2020_keyword_frame\Conf #獲取當前檔案的上上層目錄 os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 執行結果:E:\2020_keyword_frame