Python의 상대 경로

Muhammad Maisam Abbas 2023년10월10일
  1. Python의 파일 경로
  2. 절대 경로
  3. 상대 경로
Python의 상대 경로

이 자습서에서는 Python의 상대 경로에 대해 설명합니다.

Python의 파일 경로

파일 경로는 컴퓨터에서 파일의 위치를 ​​지정합니다. 예를 들어,C:\PythonProjects\Tutorials\Paths는 내 Windows 시스템에있는paths.py파일의 경로입니다. 여기에서C:\는 루트 디렉토리이고PythonProjects,TutorialsPaths는 하위 디렉토리입니다. paths.py는 루트 디렉토리C:\내의PythonProjects디렉토리에있는Tutorials디렉토리의Paths디렉토리에있는 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()method로 특정 파일의 현재 작업 디렉토리를 가져올 수 있습니다.

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.pypaths.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
Muhammad Maisam Abbas avatar Muhammad Maisam Abbas avatar

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

관련 문장 - Python Path