一、os.path.dirname()函數介紹
在Python中,os.path.dirname()函數用於獲取指定文件路徑的父級目錄。它返迴路徑的最後一個目錄名的上級目錄,可以理解為提取一個路徑字符串的目錄部分,並返回其中的父目錄。
使用os.path.dirname()函數的前提是必須相對路徑或者絕對路徑必須存在,如果指定的路徑不存在,函數將返回空值。
二、os.path.dirname()函數的用法
下面展示一個基本的使用示例,使用os.path.dirname()函數獲取當前文件的父目錄:
import os file_path = os.path.realpath(__file__) father_path = os.path.abspath(os.path.dirname(file_path)) print(father_path)
上述代碼中,首先使用os.path.realpath(__file__)獲取當前文件的絕對路徑,然後通過os.path.dirname()函數獲取該路徑的目錄部分,最後使用os.path.abspath()函數獲取該目錄的絕對路徑,從而獲取當前文件的父目錄。
三、os.path.dirname()函數的實際應用
1.在Python中創建文件和目錄
在Python中,如果需要創建一個文件或者目錄,可以使用os.path.dirname()函數獲取指定目錄的父目錄,然後使用os.path.exists()函數判斷該目錄是否已經存在,如果不存在則使用os.makedirs()函數創建目錄。
import os file_path = "file/test.txt" father_path = os.path.dirname(file_path) if not os.path.exists(father_path): os.makedirs(father_path) f = open(file_path, "w") f.write("test") f.close()
上述代碼中,首先使用os.path.dirname()函數獲取指定文件的父目錄,然後使用os.path.exists()函數和os.makedirs()函數創建該目錄,最後使用Python的文件操作函數,斷言文件並在其中寫入數據。
2.獲取當前腳本文件的上級目錄的路徑
在Python中,如果需要獲取當前腳本文件的上級目錄的路徑,可以使用os.path.dirname(__file__)函數獲取當前文件的目錄,然後使用os.path.abspath()函數獲取該目錄的絕對路徑,從而獲取當前文件的父目錄。
import os father_path = os.path.abspath(os.path.dirname(__file__)) print(father_path)
上述代碼中,首先使用os.path.dirname(__file__)函數獲取當前文件的目錄,然後通過os.path.abspath()函數獲取該目錄的絕對路徑,從而獲取當前文件的父目錄。
3.比較兩個文件的路徑
在Python中,如果需要比較兩個文件的路徑是否相同,可以使用os.path.dirname()函數獲取兩個文件路徑的父目錄,然後使用==運算符比較父目錄是否相等,從而判斷兩個文件是否在同一個目錄下。
import os file_path1 = "file1/test.txt" file_path2 = "file2/test.txt" father_path1 = os.path.abspath(os.path.dirname(file_path1)) father_path2 = os.path.abspath(os.path.dirname(file_path2)) if father_path1 == father_path2: print("兩個文件在同一個目錄下") else: print("兩個文件不在同一個目錄下")
上述代碼中,首先使用os.path.abspath()函數和os.path.dirname()函數獲取兩個文件路徑的父目錄,然後使用==運算符比較父目錄是否相等,從而判斷兩個文件是否在同一個目錄下。
四、總結
os.path.dirname()函數是Python中常用的一個函數,它能夠提取一個路徑字符串的目錄部分,並返回其中的父目錄。該函數的應用非常廣泛,例如可以用來創建文件和目錄、獲取當前腳本文件的上級目錄的路徑以及比較兩個文件的路徑等。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/184583.html