logo

Python os.chdir() 메서드

OS 모듈 Python에서는 운영 체제와 상호 작용하는 기능을 제공합니다. OS는 Python의 표준 유틸리티 모듈에 포함됩니다. 이 모듈은 운영 체제 종속 기능을 사용하는 이식 가능한 방법을 제공합니다.
os.chdir() 현재 작업 디렉터리를 지정된 경로로 변경하는 데 사용되는 Python의 메서드입니다. 새 디렉터리 경로로 단일 인수만 사용합니다.

통사론: os.chdir(경로)
매개변수:
길: 새 디렉터리 경로로 변경될 디렉터리의 전체 경로입니다.
보고: 어떤 값도 반환하지 않습니다.



코드 #1: chdir()을 사용하여 디렉토리를 변경하십시오.

파이썬3








if-else 문 자바
# Python3 program to change the> # directory of file using os.chdir() method> # import os library> import> os> # change the current directory> # to specified directory> os.chdir(r>'C:UsersGfgDesktopgeeks'>)> print>(>'Directory changed'>)>

>

>

산출:

Directory changed>

코드 #2: os.getcwd() 사용
파일의 현재 작업 디렉터리를 확인하려면 getcwd() 메서드를 사용할 수 있습니다. 경로를 변경한 후 이 방법을 사용하면 현재 작업 디렉터리의 경로를 확인할 수 있습니다.

파이썬3




# import os module> import> os> # change the current working directory> # to specified path> os.chdir(>'c:gfg_dir'>)> # verify the path using getcwd()> cwd>=> os.getcwd()> # print the current directory> print>(>'Current working directory is:'>, cwd)>

>

>

산출:

Current working directory is: c:gfg_dir>


코드 #3: 디렉터리 변경 중 오류 처리

파이썬3




# 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>:> >os.chdir(fd)> >print>(>'Inserting inside-'>, os.getcwd())> > # Caching the exception> except>:> >print>('Something wrong with specified> >directory. Exception>-> ', sys.exc_info())> > # handling with finally> finally>:> >print>(>'Restoring the path'>)> >os.chdir(cwd)> >print>(>'Current directory is-'>, os.getcwd())>

>

>

CSS의 가운데 버튼

산출:

Inserting inside- c:gfg_dirgfg Something wrong with specified directory. Exception- Restoring the path Current directory is- c:gfg_dirgfg>