logo

Metóda Python os.chdir().

modul OS v Pythone poskytuje funkcie na interakciu s operačným systémom. OS, spadá pod štandardné pomocné moduly Pythonu. Tento modul poskytuje prenosný spôsob používania funkcií závislých od operačného systému.
os.chdir() metóda v Pythone používaná na zmenu aktuálneho pracovného adresára na zadanú cestu. Ako nová cesta k adresáru je potrebný iba jeden argument.

Syntax: os.chdir(cesta)
Parametre:
cesta: Úplná cesta k adresáru, ktorá sa má zmeniť na novú cestu k adresáru.
Vrátenie: Nevracia žiadnu hodnotu



Kód #1: Na zmenu adresára použite chdir().

Python3








vracajúce polia v jazyku Java
# 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ýkon:

Directory changed>

Kód #2: Použitie os.getcwd()
Ak chcete zistiť aktuálny pracovný adresár súboru, môžete použiť metódu getcwd(). Po zmene cesty je možné pomocou tejto metódy overiť cestu k aktuálnemu pracovnému adresáru.

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ýkon:

Current working directory is: c:gfg_dir>


Kód #3: Riešenie chýb pri zmene adresára

Python3




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

ako získať aktuálny dátum v jave

>

>

Výkon:

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