Python에서 현재 디렉토리를 얻는 방법은 무엇입니까?

ItsMyCode |

이 기사에서는 Python에서 현재 디렉토리를 가져오는 방법을 살펴보겠습니다. 현재 디렉토리는 스크립트가 실행되는 작업 디렉토리에 불과합니다.

Python에서 현재 작업 디렉토리 얻기



os 모듈에는 작업 디렉토리의 절대 경로를 찾을 수 있는 getcwd() 함수가 있습니다.

*구문: * os.getcwd()

매개변수: 없음

반환 값: 현재 작업 디렉토리의 절대 경로를 포함하는 문자열을 반환합니다.

다음은 Python에서 현재 작업 디렉토리를 인쇄하는 예입니다.

# Python program get current working directory using os.getcwd()

# importing os module
import os

# Get the current directory path
current_directory = os.getcwd()

# Print the current working directory
print("Current working directory:", current_directory)



산출

Current working directory: C:\Projects\Tryouts


Python에서 스크립트 파일의 경로 얻기



현재 스크립트 파일의 경로를 얻으려면 ` __file_ `_ 변수를 사용하여 os.path 모듈의 _the _ realpath 메서드에 전달할 수 있습니다.

현재 스크립트 파일의 경로를 가져오는 예

# Python program get current working directory using os.getcwd()

# importing os module
import os

# Get the current directory path
current_directory = os.getcwd()

# Print the current working directory
print("Current working directory:", current_directory)

# Get the script path and the file name
foldername = os.path.basename(current_directory)

scriptpath = os.path.realpath( __file__ )
# Print the script file absolute path
print("Script file path is : " + scriptpath)


산출

Current working directory: C:\Projects\Tryouts
Script path is : C:\Projects\Tryouts\main.py


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



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

구문: os.chdir(경로)

매개변수:

경로: 문자열 형식의 새 디렉터리 경로입니다.

반환: 값을 반환하지 않음

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

# 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('/Projects')

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



산출

Current working directory: C:\Projects\Tryouts
New Current working directory: C:\Projects


결론



Python에서 현재 작업 디렉터리를 가져오려면 os 모듈 함수os.getcwd()를 사용하고, 현재 디렉터리를 변경하려면 os.chrdir() 메서드를 사용합니다.

게시물 How to get current directory in Python?이 ItsMyCode에 처음 나타났습니다.

좋은 웹페이지 즐겨찾기