Python os.path.abspath() 方法



os.path 模組中的 abspath(path) 方法用於獲取提供的 pathname path 的標準化絕對版本。

路徑的標準化絕對版本只不過是一個修改後的字串,它表示路徑或檔案,以便它符合目標作業系統上的有效路徑格式。這包括解析任何符號連結,如 "." 和 "..",並確保使用平臺正確的路徑分隔符(類 Unix 系統上為 "/",Windows 上為 "\")正確分隔目錄。

此方法在處理檔案路徑時特別有用,以確保檔案操作的一致性和準確性。

語法

以下是該方法的語法:

os.path.abspath(path)

引數

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

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

返回值

該方法返回一個字串,表示提供的路徑的絕對版本。

示例

讓我們探索一些示例,以瞭解 os.path.abspath() 方法的工作原理。

示例

以下示例使用 os.path.abspath() 方法獲取當前指令碼(檔案)的完整路徑。

# Import the os module
import os

# Getting the full path of the current script
result = os.path.abspath(__file__)
print(result)
print(type(result))

輸出

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

/home/cg/root/66260d93dc341/main.py
class 'str'>

示例

在這個例子中,os.path.abspath() 方法從包含 ".." 段的輸入路徑獲取規範化路徑,通常這指的是父目錄。

# Import the os module
import os 

# Getting the normalized absolute path
path = 'mydir/../myfile.txt'
normalized_path = os.path.abspath(path)

# Display the normalizedpath
print(normalized_path)

輸出

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

/home/cg/root/66260f4adb57d/myfile.txt

示例

在這個例子中,路徑與 "." 作為路徑段一起提供給 os.path.abspath() 方法以獲取規範化路徑。

# Import the os module
import os 

# Getting the normalized absolute path
path = 'mydir/./myfile.txt'
normalized_path = os.path.abspath(path)
print(normalized_path)

輸出

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

/home/cg/root/66260f4adb57d/mydir/myfile.txt

示例

在以下示例中,os.path.abspath() 方法將包含雙斜槓 "//" 的路徑修改為單個斜槓 "/",並返回 "mydir" 目錄中 "myfile.txt" 檔案的絕對路徑。

# Import the os module
import os 

# Getting the normalized absolute path
path = 'mydir//myfile.txt'
normalized_path = os.path.abspath(path)
print(normalized_path)

輸出

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

/home/cg/root/66260f4adb57d/mydir/myfile.txt
os_path_methods.htm
廣告
© . All rights reserved.