OS modul v Pythonu ponuja funkcije za interakcijo z operacijskim sistemom. OS spada pod Pythonove standardne pomožne module. Ta modul zagotavlja prenosljiv način uporabe funkcij, odvisnih od operacijskega sistema.
os.chdir() metoda v Pythonu, ki se uporablja za spremembo trenutnega delovnega imenika v določeno pot. Kot nova pot imenika potrebuje samo en argument.
Sintaksa: os.chdir(pot)
Parametri:
pot: Celotna pot imenika, ki bo spremenjena v novo pot imenika.
Vrne: Ne vrne nobene vrednosti
Koda #1: Za spremembo imenika uporabite chdir().
Python3
nadzorne strukture python
# 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'>)> |
>
>
Izhod:
Directory changed>
Koda #2: Uporaba os.getcwd()
Če želite izvedeti trenutni delovni imenik datoteke, lahko uporabite metodo getcwd(). Po spremembi poti lahko s to metodo preverite pot trenutnega delovnega imenika.
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)> |
>
>
Izhod:
linux arhitektura
Current working directory is: c:gfg_dir>
Koda #3: Odpravljanje napak med spreminjanjem imenika
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())> |
>
>
Izhod:
Inserting inside- c:gfg_dirgfg Something wrong with specified directory. Exception- Restoring the path Current directory is- c:gfg_dirgfg>