Python os.path.normpath() 方法



os.path 模組中的 normpath(path) 方法用於獲取提供的路徑名的規範化路徑名。路徑規範化包括透過刪除冗餘元件(例如額外的分隔符 (//)、對當前目錄 (./) 的引用和對父目錄 (../) 的引用)來簡化路徑名。此方法確保路徑以一致且有效的格式在不同平臺上表示。

在 Windows 作業系統上,此方法將正斜槓轉換為反斜槓,因此此規範化可能會更改包含符號連結的路徑的含義。

語法

以下是該方法的語法:

os.path.normpath(path)

引數

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

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

返回值

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

示例

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

示例

以下示例使用 os.path.normpath() 方法獲取輸入路徑“A//B/C/./../D”的規範化版本。

# Import the os module
import os 

# Normalizing a path
path = 'A//B/C/./../D'
normalized_path = os.path.normpath(path)

# Print the results 
print(normalized_path)
# Verify the type of the normpath output
print('Type of the normpath output:',type(normalized_path))

輸出

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

A/B/D
Type of the normpath output: class 'str'>
如果您在 Windows 作業系統中執行上述程式,您將獲得以下輸出。正斜槓或轉換為反斜槓。
A\B\D
Type of the normpath output: class 'str'>

示例

在此示例中,os.path.normpath() 方法用於從包含符號連結“..”的輸入路徑獲取規範化路徑,通常這指的是父目錄。

# Import the os module
import os 

# Normalizing a path
path = 'A/foo/../B'
normalized_path = os.path.normpath(path)

# Print the results 
print('The resultant normalized path:',normalized_path)

輸出

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

The resultant normalized path: A/B

示例

在此示例中,路徑以“.”作為路徑段提供給 os.path.normpath() 方法,以獲取規範化路徑。

# Import the os module
import os 

# Normalizing a path
path = 'mydir/./myfile.txt'
normalized_path = os.path.normpath(path)

# Print the results 
print('The resultant normalized path:',normalized_path)

輸出

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

The resultant normalized path: mydir/myfile.txt

示例

這是另一個使用 os.path.normpath() 方法規範化以下路徑名“D://a//b//c/../e/./myfile.txt”的示例。

# Import the os module
import os 

# Normalizing a path
path = 'D://a//b//c/../e/./myfile.txt'
normalized_path = os.path.normpath(path)

# Print the results 
print('The resultant normalized path:',normalized_path)

輸出

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

The resultant normalized path: D:/a/b/e/myfile.txt
os_path_methods.htm
廣告