在 Python 中查詢給定檔案的路徑
Python 使用者經常使用檔案,尤其是在修改、讀取或寫入檔案資料時。但是,在對檔案執行任何操作之前,都需要找到檔案的路徑。簡單來說,檔案的路徑是指檔案在系統中儲存的位置或目錄。
在 Python 中,有四種主要方法可以用來查詢給定檔案的路徑:
Pathlib 模組
OS 模組
os.path.join() 方法
os.getcwd() 方法
方法 1:使用 Pathlib 模組
Python 中的 pathlib 模組使建立檔案路徑變得非常簡單和高效。
absolute() - 絕對路徑是指包含需要訪問的檔案或目錄的完整路徑的路徑。此路徑從計算機的主目錄開始,並以需要訪問的檔案或目錄結束。
演算法
步驟 1 - 從 pathlib 模組匯入 Path 類
步驟 2 - 為檔案構造一個 Path 物件
步驟 3 - 使用 absolute() 獲取檔案的絕對路徑
步驟 4 - 這就是檔案路徑
在這個例子中,我們將學習如何使用 Python 中的 Pathlib 模組獲取完整路徑。
示例
from pathlib #Replace the file text. This path is added according to the author’s system file location file_path = Path("/tutorials_point/python.txt") absolute_path = file_path.absolute() print(absolute_path)
輸出
/home/mycomputer/tutorials_point/python.txt
方法 2:使用 OS 模組
abspath() - os.path.abspath() 函式是 os 模組中最常用的函式之一,用於確定檔案的路徑。此函式接受檔名或相對檔案路徑作為輸入,並返回絕對路徑。
演算法
步驟 1 - 匯入 os 模組
步驟 2 - 為檔案建立一個 Path 物件
步驟 3 - 使用 os.path.abspath() 獲取檔案的絕對路徑物件
在下面的示例中,我們將學習如何透過 OS 模組獲得完整路徑。
示例
import os file_name = "/home/mycomputer/tutorials_point/python.txt" abs_path = os.path.abspath(file_name) print(abs_path)
輸出
/home/mycomputer/tutorials_point/python.txt
方法 3:使用 Os.path.join() 方法
os.path.join() - Python 的 os.path.join() 方法將路徑名組合成一個完整的路徑。這意味著我們可以使用 os.path.join 方法將路徑的多個部分合併成一個,而不是手動硬編碼每個路徑名。
演算法
步驟 1 - 匯入 os 模組
步驟 2 - 單個路徑
步驟 3 - 使用 os.path.join 新增多個路徑以連線各種路徑並獲取檔案路徑
步驟 4 - 這就是檔案路徑
在下面的示例中,我們使用 os.path.join() 函式來展示其工作原理。這種方法允許我們輕鬆地根據指定位置檢索檔案的路徑。這將直接引導我們到達目標 - 準確地找到並訪問我們想要的資料夾/檔案。
示例
import os path = "/home" file_path = os.path.join(path, "mycomputer", "tutorials_point", "python.txt") print(file_path)
輸出
/home/mycomputer/tutorials_point/python.txt
方法 4:使用 Getcwd() 方法
如果我們需要確定檔案的路徑,則應考慮使用 Python 的 os.getcwd() 函式。此函式為我們提供指令碼的當前工作目錄的詳細資訊,並幫助我們在同一位置查詢檔案。
getcwd() - 此方法返回一個表示當前工作目錄 (CWD) 的字串。
演算法
步驟 1 - 匯入 os 模組
步驟 2 - 使用 getcwd() 獲取當前工作目錄
步驟 3 - 現在列印當前工作目錄
步驟 4 - 定義當前檔名
步驟 5 - 使用 os.path.join 連線當前目錄和檔名
步驟 6 - 這就是檔案路徑
獲得檔案位置的一種方法是使用 os.path.join() 方法。這裡,檔名為輸入,其路徑使用 getcwd 方法查詢,該方法告訴我們當前目錄。
示例
import os current_directory = os.getcwd() print(current_directory) file_name ="python.txt" abs_path = os.path.join(current_directory, file_name ) print(abs_path)
輸出
/home/mycomputer/tutorials_point/ /home/mycomputer/tutorials_point/python.txt
結論
我們可以使用所有這些方法來查詢 Python 的檔案路徑。這些方法用於在獨立平臺(即跨平臺設定)中工作。使用這些方法可以方便地確定檔案的路徑。