Python os.path.expanduser() 方法



Python 的 os.path.expanduser() 方法用於將路徑字串中的波浪號 (~) 字元展開到使用者的 home 目錄。它將 ~ 字元替換為使用者 home 目錄的絕對路徑。

如果找不到波浪號字元,或者沒有可用的使用者 home 目錄,則該方法將返回原始路徑字串,保持不變。

語法

以下是 Python os.path.expanduser() 方法的基本語法:

os.path.expanduser(path)

引數

此方法接受一個字串作為引數,該字串表示應將 ~ (波浪號) 字元展開到使用者 home 目錄的路徑。

返回值

該方法返回一個字串,表示路徑,其中 ~ (波浪號) 字元已展開到使用者的 home 目錄。

示例

在下面的示例中,我們使用 expanduser() 方法透過將波浪號 (~) 字元替換為使用者的 home 目錄來展開給定的檔案路徑 "path":

import os
path = "~/Documents/file.txt"
expanded_path = os.path.expanduser(path)
print(expanded_path)  

輸出

獲得的輸出如下:

C:\Users\Lenovo/Documents/file.txt

示例

此示例演示瞭如果給定路徑中有多個波浪號 (~) 符號,expanduser() 方法只展開它遇到的第一個波浪號 (~) 符號,而保留後續的符號不變:

import os
path = "~/Documents/~/Downloads"
expanded_path = os.path.expanduser(path)
print(expanded_path) 

輸出

以上程式碼的輸出如下:

C:\Users\Lenovo/Documents/~/Downloads

示例

如果我們向 expanduser() 方法提供空字串作為輸入,它將返回空字串:

import os
path = ""
expanded_path = os.path.expanduser(path)
print("The file path is:",expanded_path)     

輸出

產生的結果如下所示:

The file path is: 

示例

此示例顯示,如果在給定路徑中找不到波浪號字元,則該方法將返回原始路徑字串,保持不變:

import os
path = "/home/user/Documents/file.txt"
expanded_path = os.path.expanduser(path)
print(expanded_path)

輸出

我們獲得如下所示的輸出:

/home/user/Documents/file.txt
os_path_methods.htm
廣告