OS-moduuli Pythonissa tarjoaa toimintoja vuorovaikutukseen käyttöjärjestelmän kanssa. OS, tulee Pythonin vakioapumoduulien alle. Tämä moduuli tarjoaa kannettavan tavan käyttää käyttöjärjestelmästä riippuvia toimintoja.
os.chdir() Pythonin menetelmä, jota käytetään nykyisen työhakemiston vaihtamiseen määritettyyn polkuun. Se ottaa vain yhden argumentin uutena hakemistopoluna.
Syntaksi: os.chdir(polku)
Parametrit:
polku: Täydellinen hakemistopolku, joka vaihdetaan uuteen hakemistopolkuun.
Palautukset: Ei palauta mitään arvoa
Koodi #1: Käytä chdir() muuttaaksesi hakemistoa
Python 3
lista gimpin fonteista
# 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'> )> |
>
>
Lähtö:
Directory changed>
Koodi #2: os.getcwd()
Tietääksesi tiedoston nykyisen työhakemiston, voidaan käyttää getcwd()-menetelmää. Polun vaihtamisen jälkeen voidaan tarkistaa nykyisen työhakemiston polku tällä menetelmällä.
Python 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)> |
>
>
Lähtö:
Current working directory is: c:gfg_dir>
Koodi #3: Virheiden käsittely hakemistoa vaihdettaessa
Python 3
marquee html
# 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())> |
>
>
Lähtö:
Inserting inside- c:gfg_dirgfg Something wrong with specified directory. Exception- Restoring the path Current directory is- c:gfg_dirgfg>