Python 中的相對路徑
 
在本教程中,我們將討論 Python 中的相對路徑。
Python 中的檔案路徑
檔案路徑指定檔案在計算機中的位置。例如,C:\PythonProjects\Tutorials\Paths 是 Windows 計算機中檔案 paths.py 的路徑。在這裡,C:\是根目錄,而 PythonProjects、Tutorials 和 Paths 是子目錄。paths.py 是在根目錄 C:\內的 Paths 目錄內的 Tutorials 目錄內的 PythonProjects 目錄內的一個 python 指令碼。Python 中有兩種型別的檔案路徑,即絕對路徑和相對路徑。
Windows、Mac 和 Linux 之間的區別
在 Windows 計算機中,\用作目錄名稱之間的分隔符,而在 Linux 和 Mac 計算機中,/用作分隔符。例如,
#file path in Windows
rootdirectory\\subdirectory\\subsubdirectory\\filename.extension
#file path in Mac and Linux
rootdirectory/subdirectory/subsubdirectory/filename.extension
在 Windows 中,有兩個反斜槓,因為每個反斜槓都需要使用另一個反斜槓進行轉義。這可以通過使用 os.path.join() 方法進行管理。此方法根據作業系統處理分隔符。例如,
import os
pathname = os.path.join("root", "directory1", "directory2")
print(pathname)
輸出:
#On Windows
root\directory1\directory2
#On Mac and Linux
root/directory1/directory2
本教程將包含\作為分隔符,以在 Windows 中給出示例。我們將使用以下檔案層次結構,並將 C:\PythonProjects\Tutorials\Paths 設定為當前工作目錄。

當前工作目錄
當前的工作目錄或簡稱為 cwd 是從中執行程式的目錄。你可以通過 os.getcwd() 方法獲取特定檔案的當前工作目錄。
import os
print(os.getcwd())
輸出:
C:\PythonProjects\Tutorials\Paths
當前的工作目錄也可以在執行時使用 os.chdir() 方法進行更改。
import os
print("Old cwd = " + os.getcwd())
os.chdir("C:\\PythonProjects\\Tutorials")
print("New cwd = " + os.getcwd())
輸出:
Old cwd = C:\PythonProjects\Tutorials\Paths
New cwd = C:\PythonProjects\Tutorials
絕對路徑
檔案的絕對路徑是從根目錄到該特定檔案的完整路徑。例如,C:\PythonProjects\Tutorials\Paths\paths.py 是 paths.py 檔案的絕對路徑。
我們可以獲取當前檔案的絕對路徑,如下所示。
import os
absolutepath = os.path.abspath(__file__)
print(absolutepath)
輸出:
C:\PythonProjects\Tutorials\Paths\paths.py
使用 Python 中的絕對路徑導航到 Strings 目錄
使用 Python 中的絕對路徑導航到資料夾非常容易。唯一令人頭疼的是,你必須從根目錄中知道所有目錄的確切名稱。
import os
print("Old cwd = " + os.getcwd())
os.chdir("C:\\PythonProjects\\Tutorials\\Strings")
print("New cwd = " + os.getcwd())
相對路徑
絕對路徑是有用的,但很快就會變得複雜。因此,為了使這種複雜性最小化,使用了相對路徑。相對路徑是指某個檔案相對於當前工作目錄的路徑。
例如,如果當前工作目錄為 C:\PythonProjects\Tutorials,則 path.py 檔案的相對路徑將為\Paths\paths.py,這比絕對路徑 C:\PythonProjects\Tutorials\Paths\paths.py 更短,更容易使用。
檔案的絕對路徑在任何地方都相同,但是相對路徑根據當前工作目錄而變化。在下面的編碼示例中說明了這種現象。
使用 Python 中的相對路徑導航到 Strings 目錄
如果需要訪問 Strings 資料夾中的檔案,則必須使用完整的絕對路徑 C:\PythonProjects\Tutorials\Strings\string.py,也可以按照以下程式碼中的說明進行操作。
import os
import sys
absolutepath = os.path.abspath(__file__)
print(absolutepath)
fileDirectory = os.path.dirname(absolutepath)
print(fileDirectory)
# Path of parent directory
parentDirectory = os.path.dirname(fileDirectory)
print(parentDirectory)
# Navigate to Strings directory
newPath = os.path.join(parentDirectory, "Strings")
print(newPath)
輸出:
C:\PythonProjects\Tutorials\Paths\paths.py
C:\PythonProjects\Tutorials\Paths
C:\PythonProjects\Tutorials
C:\PythonProjects\Tutorials\Strings
Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.
LinkedIn