SW/Python

Python : 현재 작업 디렉토리 확인, 변경 방법, 예제, 명령어

얇은생각 2022. 12. 20. 07:30
반응형

Python의 디렉터리에 있는 파일을 처리할 때는 항상 절대 경로를 사용하는 것이 좋습니다. 그러나 상대 경로로 작업하는 경우, 현재 작업 디렉토리의 개념과 현재 작업 디렉토리를 찾거나 변경하는 방법을 이해해야 합니다. 절대 경로는 루트 디렉토리에서 시작하는 파일 또는 디렉토리 위치를 지정하고 상대 경로는 현재 작업 디렉토리에서 시작합니다.

Python 스크립트를 실행하면 현재 작업 디렉토리가 스크립트가 실행되는 디렉토리로 설정됩니다.

ospython 모듈은 운영 체제와 상호 작용할 수 있는 휴대용 방법을 제공합니다. 모듈은 표준 Python 라이브러리의 일부이며 현재 작업 디렉터리를 찾고 변경하는 방법을 포함합니다.

 

 

Python : 현재 작업 디렉토리 확인, 변경 방법, 예제, 명령어

 

 

Python에서 현재 작업 디렉토리 가져오기

Python의 os 모듈의 getcwd() 메서드는 현재 작업 디렉토리의 절대 경로를 포함하는 문자열을 반환합니다. 반환된 문자열에는 후행 슬래시 문자가 포함되지 않습니다.

os.getcwd()

 

 

os 모듈 메서드를 사용하려면 파일 맨 위에 있는 모듈을 가져와야 합니다.

다음은 현재 작업 디렉터리를 인쇄하는 방법을 보여 주는 예입니다.

# Import the os module
import os

# Get the current working directory
cwd = os.getcwd()

# Print the current working directory
print("Current working directory: {0}".format(cwd))

# Print the type of the returned object
print("os.getcwd() returns an object of type: {0}".format(type(cwd)))

# Current working directory: /home/jjeongil/Desktop
# os.getcwd() returns an object of type: <class 'str'>

 

 

스크립트가 있는 디렉토리를 찾으려면 os.path.realpath(_file__)를 사용하십시오. 실행 중인 스크립트에 대한 절대 경로를 포함하는 문자열을 반환합니다.

 

 

 

Python에서 현재 작업 디렉토리를 변경

Python에서 현재 작업 디렉터리를 변경하려면 chdir() 메서드를 사용하십시오.

os.getcwd(path)

 

 

메소드는 변경할 디렉터리의 경로인 하나의 인수를 허용합니다. 경로 인수는 절대 또는 상대적일 수 있습니다.

# Import the os module
import os

# Print the current working directory
print("Current working directory: {0}".format(os.getcwd()))

# Change the current working directory
os.chdir('/tmp')

# Print the current working directory
print("Current working directory: {0}".format(os.getcwd()))

# Current working directory: /home/jjeongil/Desktop
# Current working directory: /tmp

 

 

chdir() 메서드에 제공된 인수는 디렉터리여야 합니다. 그렇지 않으면 NotADirectoryError 예외가 발생합니다. 지정한 디렉터리가 없으면 FileNotFoundError 예외가 발생합니다. 스크립트를 실행하는 사용자에게 필요한 권한이 없는 경우 권한 오류 예외가 발생합니다.

# Import the os module
import os

path = '/var/www'

try:
    os.chdir(path)
    print("Current working directory: {0}".format(os.getcwd()))
except FileNotFoundError:
    print("Directory: {0} does not exist".format(path))
except NotADirectoryError:
    print("{0} is not a directory".format(path))
except PermissionError:
    print("You do not have permissions to change to {0}".format(path))

 

 

Python에서 현재 작업 디렉터리를 찾으려면 os.getcwd()를 사용하고 현재 작업 디렉터리를 변경하려면 os.chdir(path)를 사용하십시오.

반응형