OS-module in Python biedt functies voor interactie met het besturingssysteem. OS, valt onder de standaard hulpprogrammamodules van Python. Deze module biedt een draagbare manier om besturingssysteemafhankelijke functionaliteit te gebruiken.
os.chdir() methode in Python die wordt gebruikt om de huidige werkmap naar het opgegeven pad te wijzigen. Er is slechts één argument nodig als nieuw mappad.
Syntaxis: os.chdir(pad)
Parameters:
pad: Een volledig mappad dat moet worden gewijzigd in een nieuw mappad.
Geeft terug: Retourneert geen enkele waarde
Code #1: Gebruik chdir() om de map te wijzigen
Python3
hoeveel MB in een GB
# 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'> )> |
>
>
Uitgang:
Directory changed>
Code #2: Gebruik van os.getcwd()
Om de huidige werkmap van het bestand te kennen, kan de getcwd()-methode worden gebruikt. Na het wijzigen van het pad kan men met deze methode het pad van de huidige werkmap verifiëren.
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)> |
>
>
Uitgang:
retourneringstype in Java
Current working directory is: c:gfg_dir>
Code #3: Het afhandelen van de fouten tijdens het wijzigen van de map
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())> |
>
>
Uitgang:
Inserting inside- c:gfg_dirgfg Something wrong with specified directory. Exception- Restoring the path Current directory is- c:gfg_dirgfg>