有一個文件ReadConfigIni.py,這個文件的路徑是 D:\SoftWare\autoTest\AutoRunTest\Public\Common\ReadConfigIni.py

os.path.realpath(__file__)獲取當前文件的絕對路徑,__file__指當前文件,在ReadConfigIni.py文件中運行以下代碼
# 當前文件路徑 fp = os.path.realpath(__file__) print (fp) #輸出結果 D:\SoftWare\autoTest\AutoRunTest\Public\Common\ReadConfigIni.py # 其他文件路徑 fp = os.path.realpath("config.ini") print (fp) #輸出結果 D:\SoftWare\autoTest\AutoRunTest\Public\Common\config.ini
os.path.realpath("PATH")
參數說明:
1. PATH指一個文件的全路徑作為參數
2. 如果給出的是一個目錄和文件名,則輸出路徑和文件名,輸出為tuple
3. 如果給出的是一個目錄名,則輸出路徑和空文件名,輸出為tuple
實際上,該函數的分割並不智能,它僅僅是以"PATH"中的最后一個"/"作為分隔符,分隔后,將索引為0的視為目錄(路徑),
將索引為1的視為文件名
file_path = os.path.split("D:/SoftWare/autoTest/AutoRunTest/Public/Common/ReadConfigIni.py") print (file_path) # 輸出結果 # ('D:/SoftWare/autoTest/AutoRunTest/Public/Common/', 'ReadConfigIni.py') file_path = os.path.split("D:/SoftWare/autoTest/AutoRunTest/Public/Common/") print (file_path) # 輸出結果 # ('D:/SoftWare/autoTest/AutoRunTest/Public/Common/', '')
file_path = os.path.split("D:/SoftWare/autoTest/AutoRunTest/Public/Common/ReadConfigIni.py")[0] print (file_path) # 輸出結果 # D:/SoftWare/autoTest/AutoRunTest/Public/Common/ file_path = os.path.split("D:/SoftWare/autoTest/AutoRunTest/Public/Common/ReadConfigIni.py")[1] print (file_path) # 輸出結果 # ReadConfigIni.py

os.path.join()在路徑后追加
os.path.join(file_path,"config.ini")
即:D:\SoftWare\autoTest\AutoRunTest\Public\Common\config.ini
