如何在 Python 中列印當前檔案目錄的完整路徑?


當前檔案路徑是透過目錄層次結構定義的;它包含從當前檔案到該檔案所在的根目錄的回溯路徑。例如,假設一個檔案“my_file”屬於目錄“my_directory”,則此檔案的路徑定義如下

./my_directory/my_file

目錄、子目錄和檔案在路徑中都使用“/”分隔符分隔。

因此,要獲取當前檔案的完整路徑,可以使用os.path.abspath()函式。如果只需要目錄路徑,則可以呼叫os.path.dirname()方法。

使用 os.path.abspath() 方法

os.path.abspath() 函式接受路徑作為引數,用於獲取當前檔案的完整規範化絕對路徑。

示例

?以下示例演示瞭如何透過將檔名作為引數傳遞給 os.path.abspath() 方法來檢索檔案的絕對路徑。

import os
fname = "file1.txt"
print(os.path.abspath(fname))

輸出

如果我們編譯並執行上面的程式,則輸出如下所示:

/home/cg/root/33992/file1.txt

使用 os.path.dirname() 方法

os.path.dirname() 函式用於獲取當前檔案的目錄路徑(不包括檔名)。

此方法僅接受字串或位元組作為引數;但是,必須傳遞當前檔案的完整路徑才能檢索其當前目錄的路徑(路徑的一部分)。

這將得出以下結論:

return value of os.path.dirname() method + file name = return value of os.path.abspath() method

示例

在這裡,我們將首先使用 abspath() 方法獲取當前檔案的完整路徑;然後將返回值作為引數傳遞給 dirname() 方法。預計將檢索到當前目錄。

import os
fname = "file1.txt"
dn = os.path.abspath(fname)
print(os.path.dirname(dn))

輸出

如果我們編譯並執行上面的程式,則輸出將顯示如下:

/home/cg/root/78173

結論

path 模組提供兩個函式來獲取當前檔案的完整路徑。首先,使用 os.path.abspath() 函式獲取絕對路徑。接下來,使用 os.path.dirname() 函式僅獲取目錄路徑。

更新於: 2023年2月24日

17K+ 瀏覽量

開啟您的 職業生涯

透過完成課程獲得認證

立即開始
廣告