Python os.path.isabs() 方法



os.path 模組中的isabs(path) 方法用於確定給定的路徑名 path 是否為絕對路徑名。絕對路徑名是指引用目標作業系統上檔案或目錄的有效路徑名。在基於 Unix 的系統上,絕對路徑名以正斜槓 (/) 開頭,而在 Windows 上,它通常以磁碟機代號後跟反斜槓 (\) 開頭。

在處理檔案路徑時,此方法非常有用,可以確保提供的路徑是有效路徑,尤其是在處理來自不同作業系統的路徑時。

語法

以下是該方法的語法:

os.path.isabs(path)

引數

以下是其引數的詳細資訊:

  • path: 此引數表示路徑類物件,可以是表示檔案系統路徑的字串或位元組物件,也可以是實現“os.PathLike”協議的物件。

返回值

該方法返回一個布林值,其中True表示提供的路徑名 path 是絕對路徑名。False表示提供的路徑是相對路徑名。

示例

讓我們透過一些示例來了解os.path.isabs() 方法的工作原理。

示例

以下示例使用os.path.isabs() 方法來確定給定的路徑名 'D:/MyFile.txt' 是絕對路徑名還是相對路徑名。

# Import the os module
import os

# Define the path
path = 'D:/MyFile.txt'

# Check if the path is absolute
is_absolute = os.path.isabs(path)

# Print the result
if is_absolute:
    print('The given path is an absolute pathname:', path)
else:
    print('The given path is a relative pathname:', path)

輸出

執行以上程式碼後,您將獲得以下輸出:

The given path is an absolute pathname: D:/MyFile.txt
以上輸出可能因作業系統而異。

示例

在此示例中,將路徑名 "mydir/../myfile.txt" 傳遞給os.path.isabs() 方法,以確定它是絕對路徑名還是相對路徑名。

import os

# Define the path
path = 'mydir/../myfile.txt'

# Check if the path is absolute
is_absolute = os.path.isabs(path)

# Print the result
if is_absolute:
    print(f'The given "{path}" is an absolute pathname.', )
else:
    print(f'The given "{path}" is a relative pathname.')

輸出

執行以上程式碼後,您將獲得以下輸出:

The given "mydir/../myfile.txt" is a relative pathname.

示例

此示例演示瞭如何使用os.path.isabs()方法檢查標準化的絕對路徑名是絕對路徑還是相對路徑。

# Import the os module
import os 

# Normalizing a path
path = 'mydir/./myfile.txt'
normalized_abs_path = os.path.abspath(path)



# Check if the path is absolute
is_absolute = os.path.isabs(normalized_abs_path)

# Print the result
if is_absolute:
    print(f'The given "{normalized_abs_path}" is an absolute pathname.', )
else:
    print(f'The given "{normalized_abs_path}" is a relative pathname.')

輸出

在我們的線上編譯器中執行上述程式碼將得到以下輸出:

The given "/home/cg/root/66260f4adb57d/mydir/myfile.txt" is an absolute pathname.
os_path_methods.htm
廣告