Muuta nykyistä työhakemistoa Pythonilla
The OS-moduuli Pythonissa käytetään vuorovaikutukseen käyttöjärjestelmän kanssa. Tämä moduuli kuuluu Pythonin vakioapuohjelmamoduuliin, joten sitä ei tarvitse asentaa ulkoisesti. Kaikki käyttöjärjestelmämoduulin toiminnot aiheuttavat OSError-virheen, jos tiedostonimiä ja polkuja ei voida käyttää tai jos ne ovat virheellisiä tai muita argumentteja, joilla on oikea tyyppi, mutta joita käyttöjärjestelmä ei hyväksy.
Muuttaaksesi nykyinen työhakemisto (CWD) os.chdir() -menetelmää käytetään. Tämä menetelmä muuttaa CWD:n tietylle polulle. Se ottaa vain yhden argumentin uutena hakemistopoluna.
Huomautus: Nykyinen työhakemisto on kansio, jossa Python-skripti toimii.
Syntaksi: os.chdir(polku)
Parametrit:
polku: Hakemiston täydellinen polku, joka muutetaan uuteen hakemistopolkuun.
Palautukset: Ei palauta mitään arvoa
Esimerkki 1: Haemme ensin skriptin nykyisen työhakemiston ja sitten muutamme sitä. Alla toteutus.
Python 3
# Python program to change the> # current working directory> import> os> # Function to Get the current> # working directory> def> current_path():> > print> (> 'Current working directory before'> )> > print> (os.getcwd())> > print> ()> # Driver's code> # Printing CWD before> current_path()> # Changing the CWD> os.chdir(> '../'> )> # Printing CWD after> current_path()> |
Lähtö:
Current working directory before C:UsersNikhil AggarwalDesktopgfg Current working directory after C:UsersNikhil AggarwalDesktop
Esimerkki 2: Virheiden käsittely hakemistoa vaihdettaessa.
Python 3
# Python program to change the> # current working directory> # 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> :> > print> (> 'Inserting inside-'> , os.getcwd())> > os.chdir(fd)> > # Caching the exception> except> :> > print> (> 'Something wrong with specified directory. Exception- '> )> > print> (sys.exc_info())> > # handling with finally> finally> :> > print> ()> > print> (> 'Restoring the path'> )> > os.chdir(cwd)> > print> (> 'Current directory is-'> , os.getcwd())> |
Lähtö:
Lisätään sisään - C:UsersNikhil AggarwalDesktopgfg
Jotain vikaa määritetyssä hakemistossa. Poikkeus-
(, FileNotFoundError(2, 'Järjestelmä ei löydä määritettyä polkua'), )
Reitin palauttaminen
Nykyinen hakemisto on - C:UsersNikhil AggarwalDesktopgfg