그만큼 OS 모듈 Python에서는 운영 체제와 상호 작용하는 데 사용됩니다. 이 모듈은 Python의 표준 유틸리티 모듈에 포함되어 있으므로 외부에 설치할 필요가 없습니다. OS 모듈의 모든 함수는 유효하지 않거나 액세스할 수 없는 파일 이름 및 경로 또는 올바른 유형을 가지고 있지만 운영 체제에서 허용되지 않는 기타 인수의 경우 OSError를 발생시킵니다.
변경하려면 현재 작업 디렉터리(CWD) os.chdir() 메소드가 사용됩니다. 이 방법은 CWD를 지정된 경로로 변경합니다. 새 디렉터리 경로로 단일 인수만 사용합니다.
메모: 현재 작업 디렉터리는 Python 스크립트가 작동 중인 폴더입니다.
통사론: os.chdir(경로)
매개변수:
길: 새 디렉터리 경로로 변경될 디렉터리의 전체 경로입니다.
보고: 어떤 값도 반환하지 않습니다.
예시 #1: 먼저 스크립트의 현재 작업 디렉터리를 가져온 다음 이를 변경하겠습니다. 아래는 구현입니다.
파이썬3
# Python program to change the> # current working directory> import> os> # Function to Get the current> # working directory> def> current_path():> >print>(>'Current working directory before'>)> >print>(os.getcwd())> >print>()> # Driver's code> # Printing CWD before> current_path()> # Changing the CWD> os.chdir(>'../'>)> # Printing CWD after> current_path()> |
>
>
산출:
Current working directory before C:UsersNikhil AggarwalDesktopgfg Current working directory after C:UsersNikhil AggarwalDesktop>
예시 #2: 디렉터리를 변경하는 동안 오류를 처리합니다.
파이썬3
# Python program to change the> # current working directory> # importing all necessary libraries> import> sys, os> > # initial directory> cwd>=> os.getcwd()> > # some non existing directory> fd>=> 'false_dir/temp'> > # trying to insert to false directory> try>:> >print>(>'Inserting inside-'>, os.getcwd())> >os.chdir(fd)> > # Caching the exception> except>:> >print>(>'Something wrong with specified directory. Exception- '>)> >print>(sys.exc_info())> > # handling with finally> finally>:> >print>()> >print>(>'Restoring the path'>)> >os.chdir(cwd)> >print>(>'Current directory is-'>, os.getcwd())> |
자바 샘플 코드
>
>
산출:
내부 삽입 - C:UsersNikhil AggarwalDesktopgfg
지정된 디렉토리에 문제가 있습니다. 예외-
(, FileNotFoundError(2, '시스템이 지정된 경로를 찾을 수 없습니다.'), )
경로 복원
현재 디렉터리는 C:UsersNikhil AggarwalDesktopgfg입니다.