logo

Metoda Python os.chdir().

OS modul v Pythonu poskytuje funkce pro interakci s operačním systémem. OS, spadá pod standardní obslužné moduly Pythonu. Tento modul poskytuje přenosný způsob používání funkcí závislých na operačním systému.
os.chdir() metoda v Pythonu používaná ke změně aktuálního pracovního adresáře na zadanou cestu. Cesta k novému adresáři vyžaduje pouze jeden argument.

Syntax: os.chdir(cesta)
Parametry:
cesta: Úplná cesta k adresáři, která se má změnit na novou cestu k adresáři.
Vrácení: Nevrací žádnou hodnotu



Kód #1: Pomocí chdir() změňte adresář

Python3








strsep
# 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'>)>

>

>

Výstup:

Directory changed>

Kód #2: Použití os.getcwd()
Chcete-li zjistit aktuální pracovní adresář souboru, lze použít metodu getcwd(). Po změně cesty lze pomocí této metody ověřit cestu k aktuálnímu pracovnímu adresáři.

Python3




# 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)>

>

>

Výstup:

Current working directory is: c:gfg_dir>


Kód #3: Ošetření chyb při změně adresáře

Python3




negace diskrétní matematika

# 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())>

>

>

Výstup:

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