Python os.chdir() metod
OS-modul i Python tillhandahåller funktioner för att interagera med operativsystemet. OS, kommer under Pythons standardverktygsmoduler. Denna modul ger ett bärbart sätt att använda operativsystemberoende funktionalitet.
os.chdir() metod i Python som används för att ändra den aktuella arbetskatalogen till angiven sökväg. Det tar bara ett enda argument som ny katalogsökväg.
Syntax: os.chdir(sökväg)
Parametrar:
väg: En komplett sökväg till katalogen som ska ändras till ny katalogsökväg.
Returnerar: Returnerar inget värde
Kod #1: Använd chdir() för att ändra katalogen
Python3
# 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'> )> |
Produktion:
Directory changed
Kod #2: Användning av os.getcwd()
För att känna till den aktuella arbetskatalogen för filen, kan metoden getcwd() användas. Efter att ha ändrat sökvägen kan man verifiera sökvägen till den aktuella arbetskatalogen med denna metod.
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)> |
Produktion:
Current working directory is: c:gfg_dir
Kod #3: Hanterar felen när du byter katalog
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())> |
Produktion:
Inserting inside- c:gfg_dirgfg Something wrong with specified directory. Exception- Restoring the path Current directory is- c:gfg_dirgfg